text:
Can I connect my Arduino Uno to a power source and a battery at the same time?
My aim is to be able to power my Arduino while there is a power supply and if there isn't the Arduino automatically switches over to the battery. The components connected to the Arduino are pir sensor, smoke sensor, SIM 800L, temperature sensor, 6v relay.

Yes, to my knowledge this is done automatically, and there is no harm when connecting the Arduino to two power sources. When I power my Arduino I have it connected to my computer and the wall. So theoretically, if the electricity in the wall stopped coming, it would start taking power from the computer. Same works for battery.

Most mainstream and reputable Arduino variants (the UNO or Pro, for example) have protection circuitry that allows it to basically ignore where its power is coming from, as long as the voltage isn't above 20v. This is because almost every Arduino device funnels its power through an appropriate regulator, ensuring there is no problem with the voltages or available current suddenly changing (switching power feeds). However, you should account for what happens when you plug an external power source in the same loop as a battery that might be a different voltage. If you're going to try to have them manually switch then you'll need an external circuit (perhaps using a transistor that shuts off the battery when the power supply is active, with capacitors for a buffer), else you could have problems with popping batteries. But be warned, if you plug your battery into the PWR (5V/3V3) pin(s) of the Arduino, then you'll need to provide your own protection.


text:
I have cooked 3 regulators applying 12 V to RAW pin. Am I doing something wrong or did I get a bad batch?
I'm trying to make a simple keypad lock that has a 12 V magnetic lock.  I supplied 12 V to the RAW pin on the Pro Mini with plans to actuate the relay with the 5 V from VCC pin.  The lock was grounded on the terminal strip that the 12 V came from, and then the positive 12 V was switched through the relay.
Everything was working well until I powered the board through the RAW pin with 12 V.  When I did that all three failed the smoke test.
My question is, am I doing something incorrectly or did I happen to get a bad batch (all three of the boards came in the same shipment, I assume they came from the same lot)?

Can you post your circuit diagram?

And part numbers of your regulators.  What current is involved?

do you have common grounds?

The Pro Mini's 5V regulator (MIC5205) can supply a maximum of 150 mA, from which the Pro Mini uses about 20 mA, leaving around 130 mA for other applications.

Check the data sheet of the relay, to get the maximum current draw. For example, the RWH-SH-105D relay requires around 70 mA in the "on" position. While this is under the 130mA limit, you may be using other IOs or powering other modules.
To reduce the current draw, use a transistor to drive the relay like this:

Correct analysis of the problem (or at least one of them), but your solution has a bit of an issue in that it is for a relay with a 12v coil, while the poster appears to have one with a 5v coil.  So the poster will need a different relay, to find a high current regulator to power it, or perhaps to play very carefully calculated games with a power resistor in series with the relay coil.  Alternately, they may be able to use a much better transistor than the 2N3904 or perhaps a power NFET, and drive the lock solenoid directly.

A magnetic lock will be based on a solenoid, which will probably draw quite a high current from the 12 V rail. When that load is switched, a voltage spike will appear into the 12V rail due to the inductance of the supply wires. The longer the wires and the higher the current, the bigger the voltage spike.

simulate this circuit – Schematic created using CircuitLab
If the spike goes above 20V (and it can easily happen, believe me) then it will exceed the maximum rating of the MIC5205 voltage regulator and fry it unless you prevent that with some extra components. The voltage rating of the regulator input capacitor in the Pro Mini probably isn't up to the task of handling 20+ V spikes either and may be getting damaged too.
Note that the Pro Mini is specified to work with input voltages only up to 12 V, so you are operating it with no margin whatsoever! You should consider reducing that voltage in first place. You could use a DC/DC converter module to step down the 12V to a more suitable 7V and provide isolation from the spikes at the same time.
Apart from that, consider using a transient voltage suppressor (TVS or transzorb diode) and/or a large decoupling capacitor (with an adequate voltage rating) as close as possible to the input of the Pro Mini or the DC/DC converter (if you use one). You might want to try decoupling your magnetic lock with a properly selected capacitor as well.

Bonus: thermal considerations
Thermal issues shouldn't be the main culprit here, but be aware that the tiny MIC5205 can get extremely hot and enter thermal shutdown mode when operated at 12 V input voltage.
The junction to ambient thermal resistance of the regulator is 220 C/W. Its maximum operating junction temperature is 125 C. At 25 C ambient temperature that means the maximum allowable temperature rise is 100 C and the maximum allowable power dissipation is 455 mW. Because the regulator is dropping 7V, the maximum allowable current will be only 65 mA (instead of the 150 mA max that the MIC5205 can source in more favorable conditions). The consumption of the Pro Mini is around 20 mA, so that leaves you with only 45 mA for your application. You should consider whether this is enough for your application or not (some 5V relays draw around 80 mA, which will greatly exceed this 45 mA calculated limit, when connected to the VCC pin of the Pro Mini).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Understanding how methods and pointers inside a function work
After this question i starteted going deep with the theory, and started studyng step-by-step with the "Beginning C, for Arduino "
Jack Purdum.
I finished to study the functions chapter, but i still have some doubts on the code, i hope this will be not a dumb question.

Why there is a Method "Print" not a Data Type inside the Function Argument List?

static void printImuData(Print &printer, int16_t Time0,
        int16_t AcX, int16_t AcY, int16_t AcZ,
        int16_t GyX, int16_t GyY, int16_t GyZ)
{
    printer.print(Time0); printer.print(",");
    printer.print(AcX);   printer.print(",");
    [...]
}

[...]

printImuData(dataFile, Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);
if (Serial_plus_SD)
    printImuData(Serial, Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);

I though the answer was "because you can pass data to a function by-value or by-reference" in fact the first input in the argument list is the left value (memory address) of a Method, but i am very confused.
Function arguments are used to pass data to the function that it may need to perform its task.
I tried to answer to the following questions to understand the code.
1. What task does this function perform?
The function will print some data on a Serial Monitor or SD Card
2. What data do i need to send to the function?
I need to send one Method through the left value of a pointer and 7 intergers.
I can't understand why a method.
3. What data do I get back from it?
Nothing because is a void, it will perform some task inside the function (print inside the object thas is pointed?) but nothing will return to the caller.
In the book  basic example is a function that returns the value 0 or 1 if is a Leap Year.
The function argument is an int and returns an int.
void loop()
{
    if (Serial.available() > 0) {
        int bufferCount;
        int year;
        char myData[MAXCHARS + 1]; // Save room for null
        bufferCount = ReadLine(myData);
        year = atoi(myData); // Convert to int
        Serial.print("Year: ");
        Serial.print(year);
        Serial.print(" is ");
        if (IsLeapYear(year) == 0) {
            Serial.print("not ");
        }
        Serial.println("a leap year");
}
}
/*****
Purpose: Determine if a given year is a leap year
Parameters:
int yr The year to test
Return value:
int 1 if the year is a leap year, 0 otherwise
*****/
    int IsLeapYear(int yr)
    {
    if (yr % 4 == 0 && yr % 100 != 0 || yr % 400 == 0) {
        return 1; // It is a leap year
    } else {
        return 0; // not a leap year
    }
}
/*****
Purpose: Read data from serial port until a newline character is read ('\n')
Parameters:
char str[] character array that will be treated as a null-terminated string
Return value:
int the number of characters read for the string
CAUTION: This method will sit here forever if no input is read from the serial port
and no newline character is entered.
****/
int ReadLine(char str[])
    {
        char c;
        int index = 0;
        while (true) {
        if (Serial.available() > 0) {
        index = Serial.readBytesUntil('\n', str, MAXCHARS);
        str[index] = '\0'; // null termination character
        break;
        }
    }
    return index;
}

Like in my the last question, I have a civil engineer background and i am a self-taught, so is my first time with coding :)
Thank you for your patience.

I need to send one Method through the left value of a pointer and 7 intergers. The first arguments is actually a pointer to an object.

The example seems to be more about inheritance (polymorphism). You can pass any object of a class derived from the Print class to this function. HardwareSerial (the class of the Serial object) derives from the Print class. (Actually it derives from Stream which derives from Print).

"There are no stupid questions, just stupid answers"

Why there is a Method "Print" not a Data Type inside the Function Argument List?

There is no "Method" Print in the argument list.  There is a reference (not a pointer which would be a * not a &) to an object called printer that is of type Print.  The code you have provided doesn't define Print but its a could guess that it is probably something to do with printing.  By supplying the printer argument you can print this data to anything that inherits from the Print base class, Serial is a good possibility, but you could write a class that derived from Print and wrote the data to an LED matrix, etc.
I can tell its not a Method, because you are calling the print method of printer, so it has to be either a class or structure.

The function will print some data on a Serial Monitor or SD Card

I can see why you thought that but you are being too specific, it prints to anything that derives from Print, Serial and dataFile derive from it, but they might not be the only things.

I need to send one Method through the left value of a pointer and 7 integers. I can't understand why a method.

An example might help:
class CGPrinter : public Print
{
  // Some code....
  virtual void print (const char* input) {// do something}
}

void loop()
{
  CGPrinter cgp;
  printImuData (Serial, 1,2,3,4,5,6,7);
  printImuData (cgp, 1,2,3,4,5,6,7);
}

Serial is an object, a variable, a specific instance of type of class that can print data.
CGPrinter is my new super sexy printing class that will read the characters that you 'print'.  To print the 7 integers to CG's printer class is exactly the same call as the one to write it to the Serial Monitor, because both classes derive from Print.

What data do I get back from it?

Yes, correct on both points.
Does it make more sense now?  If not, just say and I'll try and clarify it.

In the argument list ex int16_t Time0 i have 1st the data type and then the rval of my variable. In the case Print &printer  i have something in the 1st place (an object that belong to the Print class) and a reference in the 2nd(something that inform the compiler about the lval of my variable referenced), but is not a Method.  A Friend of mine from CS told me that Print was a method, so i belive he was wrong, this is one reason of my confusion.

But is still not clear for me :( Inside the function you can put both a class and an object (istance of a class) that belong to that class, why? Why not only one of the two?

I'm not clear what you mean.  If you mean in the case of printImuData() you can't pass a class into the function.  A class is a type name, so try doing what you are saying with a char or an int.  If you have the function void DoStuff (int& a) can you call DoStuff (n); if int n = 4;?  Yes or course you can, but can you pass in int does DoStuff(int); make sense?  Its the same with classes if you have void OtherFunc(CHole& a); and then call CHole n; OtherFunc(n); calling OtherFunc(CHole) wouldn't make sense.

The & turns the function parameter means the variable is "passed by reference".  This means it is not copied, the address is passed to the function and it works on that memory address rather than the actual value.  This means the parameter becomes an IN/OUT value, any modifications made inside the function are passed back to the caller.  For example: void add (int a) {++a;} int a = 0; a = add(a); // a = 0 against void add (int a) {++a;} int a = 0; a = add(a); // a = 1  Note that (const int& a) in not modifiable.

Thanks for your patience. I made an error studying your answer, mea culpa, my question about the class inside the function was nosense :(
In the last comment you wrote this void add (int a) {++a;} int a = 0; a = add(a); // a = 0 against void add (int a) {++a;} int a = 0; a = add(a); // a = 1 but is the same. Maybe, if i understood , you will write this void add (int a) {++a;} int a = 0; a = add(a); // a = 0 against void add (int& a) {++a;} int a = 0; a = add(a); // a = 1 ? Thanks a lot @Code Gorilla it is very useful for me and  I'm very grateful to you :)

So, if i undestood, Print is not a method rather a data type. cgp and Serial are two objects from two different classes. I can invoke the method .print(Time0) on the two objects because they are "printable" a sort of operation like the operation of "sum" that i can do with int data types? :) Thanks :)

If you can spot my mistakes and correct them then I think you have got it :)  Sorry about that, yes you corrected it right.  Yes you are "correct" about Print.  By "correct" I mean you understanding is good enough for a beginner, but someone may come along and expand your understand later in life.  Good luck

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
It is possible to carry a pic c code for arduino
Code C for PIC16F887, I want to be able to try this code in ATMEGA328, but I do not know how, I do not know the outputs of the pic, that is, none of the pic I know.
Thank you for helping me. Grateful.
/*
Universidad del Azuay
Microcontroladores
Proyecto Piano
Autores: Juan Pablo León, Santiago Vazques
Tutor: Ing. Kenneth Samuel Palacios Baus
Fecha: 2 de enero de 2015
*/

//Declaración de Funciones
void ndo(); //Nota Do
void sdo(); //Nota Do Sostenido
void nre(); //Nota Re
void sre(); //Nota Re Sostenido
void nmi(); //Nota Mi
void nfa(); //Nota Fa
void sfa(); //Nota Fa Sostenido
void nsol(); //Nota Sol
void ssol(); //Nota Sol Sostenido
void nla();  //Nota La
void sla(); //Nota La Sostenido
void nsi(); //Nota Si
void ndo2(); //Nota Do

//Programa Principal
void main (){
osccon=0x77; //Ocilador de 8bits interno del PIC16f887

TRISC=0XFF; //Puerto C habilitamos como entrada  para las notas normales
PORTC=0;;

TRISB=0XFF; //Puerto B habilitamos como entrada para los sostenidos
PORTB=0;

TRISD=0X00; //Puerto D habilitamos como salida para el sonido del parlante
PORTD=0;

ANSELH = 0x00;
ANSEL=0x00;      // Bits AN6:AN0 como E/S digital.

    while(1){

        PORTB=0xFF;  // 255   11111111
        switch(PORTB)
        {
               case  0b00000001: sdo();  break;  //#Do
               case  0b00000010: sre();  break;  //#Re
               case  0b00000100: sfa();  break;  //#Fa
               case  0b00001000: ssol(); break;  //#Sol
               case  0b00010000: sla();  break;  //#La
        }

        PORTC=0xFF;  // 255   11111111
        switch(PORTC)
        {
               case  0b00000001: ndo();  break;  //Do
               case  0b00000010: nre();  break;  //Re
               case  0b00000100: nmi();  break;  //Mi
               case  0b00001000: nfa();  break;  //Fa
               case  0b00010000: nsol(); break;  //Sol
               case  0b00100000: nla();  break;  //La
               case  0b01000000: nsi();  break;  //Si
               case  0b10000000: ndo2(); break;  //Do
        }
    }

}

void ndo(){      //Do
        PORTD=1;
        delay_us (1911);
        PORTD=0;
        delay_us (1911);
}

void sdo(){      //#Do
        PORTD=1;
        delay_us (1804);
        PORTD=0;
        delay_us (1804);
}

void nre(){     //Re
        PORTD=1;
        delay_us (1702);
        PORTD=0;
        delay_us (1702);
}

void sre(){     //#Re
        PORTD=1;
        delay_us (1607);
        PORTD=0;
        delay_us (1607);
}

void nmi(){     //Mi
        PORTD=1;
        delay_us (1517);
        PORTD=0;
        delay_us (1517);
}

void nfa(){     //Fa
        PORTD=1;
        delay_us (1432);
        PORTD=0;
        delay_us (1432);
}

void sfa(){     //#Fa
        PORTD=1;
        delay_us (1351);
        PORTD=0;
        delay_us (1351);
}

void nsol(){    //Sol
        PORTD=1;
        delay_us (1276);
        PORTD=0;
        delay_us (1276);
}

void ssol(){    //#Sol
        PORTD=1;
        delay_us (1203);
        PORTD=0;
        delay_us (1203);
}
void nla(){     //La
        PORTD=1;
        delay_us (1136);
        PORTD=0;
        delay_us (1136);
}

void sla(){    //#La
        PORTD=1;
        delay_us (1121);
        PORTD=0;
        delay_us (1121);
}

void nsi(){    //Si
        PORTD=1;
        delay_us (1012);
        PORTD=0;
        delay_us (1012);
}

void ndo2(){   //Do
        PORTD=1;
        delay_us (955);
        PORTD=0;
        delay_us (955);
}

Code file taken from this video: https://www.youtube.com/watch?v=2jVZnKjCltw

There are two things you need to learn:

What the instructions in the PIC program mean, and
What the equivalent instructions (or functions for abstracted concepts) are in the Arduino API.

For instance, it looks like you may be making sounds of specific pitches. For that you would replace much of your code with the tone() function.
Reading IO pins would be done with digitalRead(), and pinMode() to set them to INPUT mode.
Basic C constructs like switch, and if() { } else { } etc are the same, but given the abstractions the Arduino API gives you it's probable you'd be using them in different ways anyway.
So in a nutshell: learn what your program is doing, then write the equivalent program for the Arduino.

No, you can not run Microchip PIC16F887 on an Atmel ATMEGA328 directly.  Any code that does useful work likely interfaces with the "outside world" through the processor's inputs and outputs (ADC, GPIO, ect).  It is very unlikely any two processor designs approach interfacing to the outside world in the same way.
The process of recoding software / firmware to run on different processors is called porting.  It is a time consuming and costly process which is repeated over and over again.  Porting is most often done because people or companies want to use the same software / firmware despite changing hardware due to speed increases, size reductions or cost reductions.


text:
Use SPI and I2C in the same circuit (ATtiny85/84)
There is a previous question about this same topic here, but it does not answer my question.
I want to use a generic I2C OLED 128x64 px display and an SPI RF24 radio in the same sketch. I know that it's theoretically possible to do so as long as they're not used at the same time - my question concerns the implementation of this circuit. Can I just leave the two devices as-is without needing some kind of external apparatus to switch power to each one of them?
I know that for SPI a chip will just ignore everything when its CS pin is pulled high, and from my tests the SPI communications don't affect the SDA line of the I2C - the problem comes when I try and use the CLK and SCL line with this setup. The pullup resistor in my circuit is stopping the I2C SCL line from working. When I remove the wire (green in the breadboard schematic shown) that connects the CLK to one end of the diode the I2C starts working and the display updates, but the radio doesn't work. If I remove the pullup resistor from the circuit the I2C starts working again, but the radio doesn't work anymore. I tried switching the CLK signal with a transistor, but it doesn't look like the 2n2222 transistor I was using is fast enough to switch the CLK signal. Will I have to go with the tiny84, or is there a way to get this to work on the ATtiny85?

Do you have a AtTiny 85 of 84? They are quite different, you know. Which pins do you need to use for I2C? Which pins do you need to use for SPI?

ATtiny8X does not have specific hardware support for SPI and I2C instead there is a hardware module called USI that can be used to implement SPI and I2C. Your alternative is to use USI for one of the protocols (for instance I2C) and additional pins for software SPI.

I2C should ignore any commands that don't make sense or aren't addressed to it; you can share

Alex - I2C uses addresses rather than a CS line, so the first(?) byte of the message says who the messages is for.  Each device has two addresses, a read and a write address which is actually only different in bit7.  Don't forget you 4.7K pull-ups on the SDA and SCL lines.

@CodeGorilla ok thanks. I isolated the problem that's not allowing my setup  to work and updated my question.

In the setup shown, you have 3 pins free, yes? Although hardware i2c may not be directly possible through software, the use of the other GPIO pins can be used for either a logic circuit to switch around the pull up resistor/green wire/whatever OR you can just use software i2c which is a lot easier to do.


text:
Arduino ISP ATtiny problems
As I was trying to program my ATtiny chip with my arduino, I ran across some problems. Note that I know that this problem is faced almost in every Q and A site and forum so don't flag me as repeat yet. (I was trying to burn the bootloader so my chip runs at 8MHz)
So this is the error code:
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -v -v -v -pattiny85 -cstk500v1 -PCOM1 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0xe2:m

 avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

 System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM1
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

avrdude done.  Thank you.

Error while burning bootloader.

* deleted attempt 2 to 9 *
Although a solution to this problem will be very nice, that is not my intention here. I tried almost all solutions I have found and non of them work, and I want to know why. So these are my questions:

What does this code actually mean? The for example the "programmer", is it referring to the Arduino or the ATtiny(or the highly unlikely, laptop that im using.)
How do I access more error codes, if there are any, as I think that these codes really do not tell that much.
[Solved]To prevent Arduino from auto-resetting, almost all tutorials connect the Reset pin to the Ground pin with a 10uF capacitor, and I don't have one. I tried with various other capacitors that I have(22uF, 0.4uF, 0.22uF, 47uF, and 330uF). I do not know how does the capacitance affect the anti auto-resetting function, so some explanation here is helpful.
[solved]

EDIT: I disconnected the ATtiny and the same error code persists. This, I conclude as either I never had a proper connection with the ATtiny, or the problem is with the communication of my laptop with the Arduino.

You need to select the correct programmer in them menu. You need to select Aruino as ISP. Also try the "upload using programmer" option.

@Gerben I am on Arduino as ISP. I just tried the upload using programmer, but same error code.

Re 10μF capacitor, a 22μF should work in its place.    See ArduinoISP on Uno requires 10uF cap -- WHY? on arduino.cc for more.

@JamesWaldby-jwpat7 I have been looking for something like this for ages. Thanks James. Now that's one problem out of the way.

I did not download Arduino as ISP into my arduino. I realize how much of an idiot I am. The capacitor wasn't even needed for some reasons. I might make an intensive tutorial on this project.

I love asian tech culture. NO SHAME IN MAKING A MISTAKE! If LadyAda were asian, the PIs would have pinout text on the boards. +1


text:
Cannot obtain reading from meter (Modbus)
I have a system in which I am taking readings from a meter and processing it through an Arduino Nano. My code looks as follows:
#include <SoftwareSerial.h>

#define SerialControl 7
#define RS485Tx HIGH
#define RS485Rx LOW

SoftwareSerial RS485Serial(11, 12);
uint8_t window[8]; // Initialising window of 8 bytes

byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };

// 0x01: Meter Address, 0x03: Read Function Code, 0x40: Register Address Variable (Start address high bit)
// 0x34: Register Address Variable (Start address low bit)
// 0x00: Register Quantity (High Bit), 0x02: Register Quantity (Low Bit)
// 0x90: CRC check code (CRC code Low bit)
// 0x05: CRC check code (CRC code High bit)

void dumpWin() {
  for (int i = 0; i < 8; i++) {
    Serial.print(window[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

void ReadRx() {
  // Sliding Window Implementation for reading data
  if(RS485Serial.available()) {
    uint8_t b = RS485Serial.read();
    dumpWin();
    // Slide the contents of the array down
    for (uint8_t i = 0; i < 7; i++) {
      window[i] = window[i+1];
    }
    window[7] = b; // Next frame inserted at the top of previous
    if ((window[0] == 0x01) && (window[1] == 0x03) &&
      (window[2] == 0x40) && (window[3] == 0x34)) {
      // Doing something with window[4] and window[5] here
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(SerialControl, OUTPUT);
  RS485Serial.begin(9600);
}

void loop() {
  static uint32_t ts = millis();
  if (millis() - ts >= 2000) {
    ts = millis();
    digitalWrite(SerialControl, RS485Tx);
    RS485Serial.write(SendKWh, sizeof(SendKWh));
    RS485Serial.flush();
    digitalWrite(SerialControl, RS485Rx);
    RS485Serial.listen();
  }
  ReadRx();
}

The ReadRx() is behaving odd and dumpWin() is giving 0 0 0 0 0 0 0 0 output. I have been trying but I'm not able to figure out where am I going wrong. Your help is appreciated!
EDIT 2: I changed the code as suggested by @Majenko but still window[] O/P is 0 for all. I am not able to understand as to why it is not able to read the values from RS485Serial.

Don't have all those delays. You don't want any delays anywhere.

Delay in ReadRx after digitalWrite ?

ReadRX only reads one byte. It needs to be run repeatedly and fast. Leave the rs485 in RX mode all the time except when you specifically want to transmit.

I removed delay(1500) and still the O/P for dumpWin() remains 0 for all.

Is there anything wrong in this statement RS485Serial.write(SendKWh, sizeof(SendKWh));

I think your whole method of working is wrong. In loop you should have a bit of code that decides if it's time to send. That then switches to send mode, sends, then switches back to read mode. Then all that is left in loop is the reading function, which just reads, adds to the array, and processes if it matches. Nothing else.

You need to stop thinking quite so linearly. You are working with asynchronous systems, so your code has to be asynchronous too.
Something more like this:
#include <SoftwareSerial.h>

#define SerialControl 7

#define RS485Tx HIGH
#define RS485Rx LOW

SoftwareSerial RS485Serial(11, 12);

byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };

// 0x01: Meter Address, 0x03: Read Function Code, 0x40: Register Address Variable (Start address high bit)
// 0x34: Register Address Variable (Start address low bit)
// 0x00: Register Quantity (High Bit), 0x02: Register Quantity (Low Bit)
// 0x90: CRC check code (CRC code Low bit)
// 0x05: CRC check code (CRC code High bit)

uint8_t window[8]; // Initialising window of 8 bytes

void dumpWin() {
  for (int i = 0; i < 8; i++) {
    Serial.print(window[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

void ReadRx() {
  if(RS485Serial.available()) {
    uint8_t b = RS485Serial.read();
    dumpWin();
    // Slide the contents of the array down
    for (uint8_t i = 0; i < 7; i++) {
      window[i] = window[i+1];
    }

    window[7] = b; // Next frame inserted at the top of previous

    if ((window[0] == 0x01) && (window[1] == 0x03) &&
        (window[2] == 0x40) && (window[3] == 0x34)) {
          // Doing something with window[4] and window[5] here
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(SerialControl, OUTPUT);
  digitalWrite(SerialControl, RS485Rx);
  RS485Serial.begin(9600);

}

void loop() {
  static uint32_t ts = millis();

  if (millis() - ts >= 2000) {
      ts = millis();
      digitalWrite(SerialControl, RS485Tx);
      RS485Serial.write(SendKWh, sizeof(SendKWh));
      RS485Serial.flush();
      digitalWrite(SerialControl, RS485Rx);
      RS485Serial.listen();
  }

  ReadRx();
}

Notice how I use millis() to send the command every 2 seconds asynchronously (i.e., without delay()). The RS485 is kept in READ mode except for the brief moment while you send. Also note the use of flush()  to wait until the last symbol has been transmitted by the UART (software in this case) interface. It's important, otherwise you may cut off the transmission part way through (I don't think it's such a problem with SoftwareSerial, but with a hardware UART missing it out would be fatal).
The reading just reads one character and returns to the loop. Each iteration through the loop will (if a character is available) read just one character. Only when all 8 have been received and the contents of the window match up can you process anything (which you would put in place of the comment).
This method also leaves you free to implement other things in loop(), as long as they don't use delay() as well.


text:
ToF Laser Sensor (VL53L0X) not working
I have this time of flight laser distance sensor: http://www.dx.com/de/p/cjmcu-vl53l0x-tof-laser-distance-measuring-sensor-module-purple-449081#.WSbn52jyi70
The example code of the VL53L0X-arduino library is not working; I always get the serial message

65535 TIMEOUT

However, I guess that the problem is at the sensor. The communication is via I2C, so that the i2c scanner should find it's address, right?
This finder doesnot find any address - am I right, that then the problem is at the sensor?
I connected VCC to (nearly) 5V, GND to GND, SCL to A5 and SDA to A4 (Arduino Uno)

It look like that board doesn't have pull-up resistors on the SDA & SCL pins. Try adding them. Something around 2 kilo-ohm (not that critical).

@Gerben I tried it. I added for SDA & SCL 2.2 kOhm resistors to pull it to 5V. However, I still get 65535 TIMEOUT. But do you agree, that I should get an address using the I2C scanner?

Yes. It should appear on the scanner. Looking at the listing, it specifies that it is a 3.3V device. But looking at the pictures it seems like there is a voltage regulator and something like a buffer-ic on the bottom.

Why have you connected it to 5V?

have you solved the problem? I have the same.

@Mcrane unfortunately not. Please leave a reply if you do

I had the same problem using this sensor. The solution was to connect

VCC -> 5V
GND -> GND
SCL -> A5 (SCL)
SDA -> A4 (SDA)
DNC -x Not connected
GN2 -> GND
XSH -> 5V
INT -x Not connected

And then to use the code mentioned here by Ted Meyers. I used Nano with ATmega328P and Arduino IDE 1.8.5.

CODE:
#include <Wire.h>

#define VL53L0X_REG_IDENTIFICATION_MODEL_ID         0xc0
#define VL53L0X_REG_IDENTIFICATION_REVISION_ID      0xc2
#define VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD   0x50
#define VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD 0x70
#define VL53L0X_REG_SYSRANGE_START                  0x00
#define VL53L0X_REG_RESULT_INTERRUPT_STATUS         0x13
#define VL53L0X_REG_RESULT_RANGE_STATUS             0x14
#define address 0x29

byte gbuf[16];

void setup() {
  // put your setup code here, to run once:
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
  Serial.println("VLX53LOX test started.");
}

void loop() {
  Serial.println("----- START TEST ----");
  test();
  Serial.println("----- END TEST ----");
  Serial.println("");
  delay(4000);
}

void test() {
  byte val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_REVISION_ID);
  Serial.print("Revision ID: "); Serial.println(val1);

  val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_MODEL_ID);
  Serial.print("Device ID: "); Serial.println(val1);

  val1 = read_byte_data_at(VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD);
  Serial.print("PRE_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
  Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

  val1 = read_byte_data_at(VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD);
  Serial.print("FINAL_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
  Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

  write_byte_data_at(VL53L0X_REG_SYSRANGE_START, 0x01);

  byte val = 0;
  int cnt = 0;
  while (cnt < 100) { // 1 second waiting time max
    delay(10);
    val = read_byte_data_at(VL53L0X_REG_RESULT_RANGE_STATUS);
    if (val & 0x01) break;
    cnt++;
  }
  if (val & 0x01) Serial.println("ready"); else Serial.println("not ready");

  read_block_data_at(0x14, 12);
  uint16_t acnt = makeuint16(gbuf[7], gbuf[6]);
  uint16_t scnt = makeuint16(gbuf[9], gbuf[8]);
  uint16_t dist = makeuint16(gbuf[11], gbuf[10]);
  byte DeviceRangeStatusInternal = ((gbuf[0] & 0x78) >> 3);

  Serial.print("ambient count: "); Serial.println(acnt);
  Serial.print("signal count: ");  Serial.println(scnt);
  Serial.print("distance ");       Serial.println(dist);
  Serial.print("status: ");        Serial.println(DeviceRangeStatusInternal);
}

uint16_t bswap(byte b[]) {
  // Big Endian unsigned short to little endian unsigned short
  uint16_t val = ((b[0] << 8) & b[1]);
  return val;
}

uint16_t makeuint16(int lsb, int msb) {
    return ((msb & 0xFF) << 8) | (lsb & 0xFF);
}

void write_byte_data(byte data) {
  Wire.beginTransmission(address);
  Wire.write(data);
  Wire.endTransmission();
}

void write_byte_data_at(byte reg, byte data) {
  // write data word at address and register
  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.write(data);
  Wire.endTransmission();
}

void write_word_data_at(byte reg, uint16_t data) {
  // write data word at address and register
  byte b0 = (data &0xFF);
  byte b1 = ((data >> 8) && 0xFF);

  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.write(b0);
  Wire.write(b1);
  Wire.endTransmission();
}

byte read_byte_data() {
  Wire.requestFrom(address, 1);
  while (Wire.available() < 1) delay(1);
  byte b = Wire.read();
  return b;
}

byte read_byte_data_at(byte reg) {
  //write_byte_data((byte)0x00);
  write_byte_data(reg);
  Wire.requestFrom(address, 1);
  while (Wire.available() < 1) delay(1);
  byte b = Wire.read();
  return b;
}

uint16_t read_word_data_at(byte reg) {
  write_byte_data(reg);
  Wire.requestFrom(address, 2);
  while (Wire.available() < 2) delay(1);
  gbuf[0] = Wire.read();
  gbuf[1] = Wire.read();
  return bswap(gbuf);
}

void read_block_data_at(byte reg, int sz) {
  int i = 0;
  write_byte_data(reg);
  Wire.requestFrom(address, sz);
  for (i=0; i<sz; i++) {
    while (Wire.available() < 1) delay(1);
    gbuf[i] = Wire.read();
  }
}

uint16_t VL53L0X_decode_vcsel_period(short vcsel_period_reg) {
  // Converts the encoded VCSEL period register value into the real
  // period in PLL clocks
  uint16_t vcsel_period_pclks = (vcsel_period_reg + 1) << 1;
  return vcsel_period_pclks;
}

You have to pull XSH high (3.3V) in order to turn the device on (either via an I/O port or via a pullup resistor to 3.3V).
Also, the device is rated for a maximum of 3.3V, you might damage it if you connect it to 5V.
Regards

One other thing to check as I had this error myself and it was simply because I hadn't soldered the header pins of the nano or the TOF device which I had just stuck into my breadboard. I am using a iHaospace VL53l0x from Amazon. I only thought of it once I ran the i2C scanner check, which didn't recognise (see) the device, so that go me thinking - (https://gammon.com.au/i2c). The I2C scanner Sketch code to use in Arduino's IDE is two thirds down that page. I also should point out that you need to run the serial monitor at the 115200 baud rate not lower or you might get gobbledygook. Now it all works just as it should with the standard Arduino Adafruit example, no #include wire.h required.

I had this problem. After connecting VL53L0X, the script hung at the start. Scanning of i2c devices also hung up. Washing the soldering points of contacts helped. Apparently the device is very sensitive to dirt on the contacts.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What do I do with the potentiometer on Adafruit RGB LCD
So I just got my Adafruit RGB backlight positive LCD 16x2 + extras - black on RGB In this picture it shows a potentiometer beside the LCD. Anyone know where this is supposed to go?

If it helps, I'm mounting the shields on an Adafruit I2C Controlled + Keypad Shield Kit for 16x2 LCD

It goes the same place as for any other LCD. Just because the backlight is an RGB LED doesn't change how the LCD functions.

It's the same pot (functionally) as the orange one in the shield kit.

The potentiometer is for setting the contrast level of the LCD. The Shield Kit shown also comes with a pot (the one with the orange face). Assembled it should look like this:

Notice the pot in the lower right corner to the right of the microcontroller ic and above the reset button.

The contrast is set by inputting an analog voltage into Pin 3 on the LCD header. The analog voltage is created using the potentiometer and is easily adjusted by the user when in operation.
The diagram below shows (only) the circuit needed to adjust the contrast on the LCD display.


text:
I want to declare an array with variable size and also I want to ask from the user to enter it?
I'm using C++ language.
double coordinates [length][5];

What have you tried so far? Would you please show more of your code?Did you take a look at C++ new operator?

You can not declare an array of variable length unless you do dynamic memory allocation.  Dynamic memory allocation on an embedded platform is not a good idea, so it is better to fix the 'length' of the array to a sensible limit.

You'll have to dynamically allocate it.
int length;
double **coordinates;
cin >> length;
coordinates = new double*[length];
for (int i = 0; i < length; i ++ {
    coordinates[i] = new double[5];
}

so then I have to close it at the end of my code.

Indeed you will.

I'd love to say this will crash, but it won't compile.  cin doesn't exist on an Arduino unless you have got a port of the std lib.   The memory you allocate needs freeing. Finally allowing a user to enter an unrestricted value for length is asking for a crash.  Enter 1,000,000 if your doubt me :)

That's fair. But it was tagged c++, so that's how I answered. IMHO, this question should be migrated to Stack Overflow.


text:
Can't use two SPI devices at the same time
I can use the MFRC522 using the following code:
#include <SPI.h>
#include <MFRC522.h>

MFRC522 mfrc522(10, 9);

void setup() {
    SPI.begin();
    mfrc522.PCD_Init();
}

void loop() {
    if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
         // Do stuff
    }
}

And it works great. I can also use the dot-matrix (8x8) using the following code:
#include "LedControl.h"

LedControl lc = LedControl(12,11,8,1);

void setup() {
    lc.shutdown(0,false);
    lc.setIntensity(0,3);
    lc.clearDisplay(0);

    lc.setLed(0,2,5,true);
    lc.setLed(0,5,5,true);

    lc.setLed(0,2,2,true);
    lc.setLed(0,3,1,true);
    lc.setLed(0,4,1,true);
    lc.setLed(0,5,2,true);
}

void loop() {
}

And it works just fine as well. However, when I try to use both of them using the following code:
#include <SPI.h>
#include <MFRC522.h>
#include "LedControl.h"

LedControl lc = LedControl(12,11,8,1);
MFRC522 mfrc522(10, 9);

void setup() {
    SPI.begin();
    mfrc522.PCD_Init();

    lc.shutdown(0,false);
    lc.setIntensity(0,3);
    lc.clearDisplay(0);

    lc.setLed(0,2,5,true);
    lc.setLed(0,5,5,true);

    lc.setLed(0,2,2,true);
    lc.setLed(0,3,1,true);
    lc.setLed(0,4,1,true);
    lc.setLed(0,5,2,true);
}

void loop() {
    if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
         // Do stuff
    }
}

In that case only one of them works (the MFRC522). I know that since they are connected in SPI mode they need to have different SS pins, so I used pin 10 for MFRC522 and pin 8 for dot-matrix. So, what's wrong? Why dot-matrix doesn't work at the same code with MFRC522??

The LedControl doesn't use SPI library but it's using shiftOut internally. So you can't use them both at the same pins as the SPI interface takes over them.
Basically SPI.begin() takes over the control on its pins and that means when you use digitalWrite or pinMode on those pins, it'll be ignored (at least on some of them).
If you add SPI.begin() into the second example (LedControl one) it'll stop working. However you can change pins for LedControl to other (free) pins and it should be working again.
And also there are mixed signals between both devices:
HW SPI wiring:
13  CLK    output
12  MISO   input
11  MOSI   output
9   SS     output

and LedControl wiring is:
12  MOSI   output (not really)
11  CLK    output

Something from the datasheet about alternate pin functions:

SCK/PCINT5 – Port B, Bit 5
  SCK: Master Clock output, Slave Clock input pin for SPI channel. When the SPI is enabled as a
  Slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is
  enabled as a Master, the data direction of this pin is controlled by DDB5. When the pin is forced
  by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit.
  PCINT5: Pin Change Interrupt source 5. The PB5 pin can serve as an external interrupt source.
MISO/PCINT4 – Port B, Bit 4
  MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI is enabled as a
  Master, this pin is configured as an input regardless of the setting of DDB4. When the SPI is
  enabled as a Slave, the data direction of this pin is controlled by DDB4. When the pin is forced
  by the SPI to be an input, the pull-up can still be controlled by the PORTB4 bit.
  PCINT4: Pin Change Interrupt source 4. The PB4 pin can serve as an external interrupt source.
MOSI/OC2/PCINT3 – Port B, Bit 3
  MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI is enabled as a
  Slave, this pin is configured as an input regardless of the setting of DDB3. When the SPI is
  enabled as a Master, the data direction of this pin is controlled by DDB3. When the pin is forced
  by the SPI to be an input, the pull-up can still be controlled by the PORTB3 bit.
  OC2, Output Compare Match Output: The PB3 pin can serve as an external output for the
  Timer/Counter2 Compare Match. The PB3 pin has to be configured as an output (DDB3 set
  (one)) to serve this function. The OC2 pin is also the output pin for the PWM mode timer
  function.
  PCINT3: Pin Change Interrupt source 3. The PB3 pin can serve as an external interrupt source.
SS/OC1B/PCINT2 – Port B, Bit 2
  SS: Slave Select input. When the SPI is enabled as a Slave, this pin is configured as an input
  regardless of the setting of DDB2. As a Slave, the SPI is activated when this pin is driven low.
  When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB2. When
  the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB2 bit.
  OC1B, Output Compare Match output: The PB2 pin can serve as an external output for the
  Timer/Counter1 Compare Match B. The PB2 pin has to be configured as an output (DDB2 set
  (one)) to serve this function. The OC1B pin is also the output pin for the PWM mode timer
  function.
  PCINT2: Pin Change Interrupt source 2. The PB2 pin can serve as an external interrupt source.

"So you can't use them both at the same pins" But I don't use them both at them same SS pin. I use pin 8 and pin 10.

@DimChtz: You have configured HW SPI interface (on pins 10,11,12,13), so it just can't be used with software implementation of SPI (by LedControl int pins 11 and 12). Maybe just try to add SPI.begin() into the second code example (LedControl only one)

I am confused. Does this mean I can't use 2 spi devices in the same code? That's weird. And if I add SPI.begin() into the ledcontrol only code leds won't work.

@DimChtz You can use more SPI devices with HARDWARE SPI (just with different SS). But you can't combine libraries that uses HARDWARE SPI with libraries that uses SOFTWARE SPI on same pins.

@KIIV, you could edit info from comments into answer.

Is there any solution or it's impossible to use both dot matrix and mfrc at the same time?

@DimChtz yes, there is a solution - use LedControl on other pins than 11,12,13

Okay, I changed ledControl 11,12 to 6,7 and it works. THanks !!


text:
Arduino Due power supply
I have an Arduino Due.  It communicate to the computer with the native usb port. It is also powered by the native port. Anyway, the connected sensors are pretty sensitive to the current, thus I would like to use a power supply (as a portable smartphone charger) in order to provide the current at the Arduino.
How can I say to the Arduino to get the current from another 'port' (e.g. the serial programming) and use the native port only for the communications?

You can't really fiddle with the power circuitry of the Due. If external sensors need more power than the due can provide through its internal 5V connection, whatever you choose that to be (dictated by the USB connection used) then you will either have to use a higher voltage to feed the barrel jack, or better, power the sensors separately to the Due. Just remember to connect the grounds.

beside, the USB power selector on the Arduino 2 is pretty crappy. The serial programming port has a pMOSFET connected as an "ideal diode" (gate grounded, drain toward the power). The other port has a similar connection, except that the gate is driven by a comparator circuit. However if Vin=0, the comparator outputs 0, and drives the gate low. The problem is that a mosfet connected as an "ideal diode", once it's on, it also conducts backwards, as long as VGS > VTH. Therefore current can flow between the VDD of two USB ports... Yes, the same can occur with external VIn and the serial USB.


text:
Doubt on Processing Power
The datasheet of arduino mega claimed that the board has 16Mhz processing power. But the question that doubt me is what would happen to the board if the board has no enough processing power.
For example,  if the board is used in an application that involves a lot of calculation in each loop. Would it stall the board?
Personally, i think the board would just give slower response instead of stalling the board. It was due request is done in sequential method in the code. Therefore it would not accumulate up the request until stalling the device like PC and I think it would be just at most an arduino which is always busy.
Is it what would happen if the board has no enough processing power?

The Arduino doesn't multi-task like your PC does. How it behaves is entirely dependent on how you write your sketch. If you write it such that it gets stuck for long periods processing and not responding to input, then that's what it'll do. If you write it to respond to input rapidly and do processing in small chunks in between, it'll do that. Does that answer your question or help understand the situation better?

Processing Power is a bit of a misnomer. Clock Frequency is a better description.
In general one assembly instruction gets executed each clock cycle. That means approximately 16 million instructions per second (there are a couple that take more than 1).
Your C program gets compiled into those instructions and executed at 16 million instructions per second.
If your routine is 16 million instructions long (when loops are unrolled) then it will take 1 second to execute.
Unlike a PC, which is constantly switching between tasks, an Arduino does only one thing, and that is the one thing you programmed it to do. Because of that execution time is predictable. If it took 1 second to execute today it will take 1 second tomorrow,  and 1 second next week.


text:
Reading and processing a PWM on AtTiny45
I have this question and I can't find answers!
I wanted to use an AtTiny45V (due to low voltage requirements, it will run at 1.8 volts) to read a PWM from an Arduino, and then process this information.
Explained better:
let's say, I hook up one pin of the AtTiny to an Arduino pin (named connection), and in the IDE I write:
AnalogWrite(connection,X)

I want the AtTiny to write high on a port based on the X value.
Example:
X = 20 writes high on AtTiny PB5
X = 25 writes high on AtTiny PB5 and PB3
etc...
So, basically I want to read the duty cycle from the Arduino PWM and let the AtTiny do something based on duty cycle value.
Is this possible?
Thanks

What is the switching frequency of your pwm? How fast do you want to respond?

I'll be using the default PWM frequency of Arduino (490Hz or 980Hz, pin-dependant). For the response time I don't need it to respond in real-time, but also not taking ages for responding!

Your question is confusing though. You say you want your secondary mcu (the attiny) to set a pin high when the primary mcu (arduino) sets a pin high, but then you go on to say you want to measure duty cycles. One is just mirroring a pin state, the other is measuring the pin state over time. The former is much easier because time isn't part of the equation.

@gregb212 I want to set a different pin high/low on the secondary mcu based on what duty cycle the primary mcu has in output: I'll define a protocol in which some duty cycles will be associated to a pin state change

No, he says for a different PWM value he will raise different pins.

@TodorSimeonov Exactly!

You could set up two ISRs.  One increases a counter every time the pin changes on the 45 (high-to-low or low-to-high), and the other when a timer (say Timer0) overflows.  When the timer overflows, you can have a function that turns on pins based on the counter value.

@calcium3000 your solution can measure frequency, but his frequency is constant. He needs to read the PWM value.

@Ghesio take a look at the AVR135 app note from Atmel - http://www.atmel.com/Images/Atmel-8014-Using-Timer-Capture-to-Measure-PWM-Duty-Cycle_ApplicationNote_AVR135.pdf

It can be used also on attiny? I'm fairly new to avr world

@Ghesio, don't know. I have never used an Atmel MCU. so far worked only on PICs. But IMHO you should get a timer, start it with interrupt on rising edge and then on falling edge another interrupt should read the timer count. Something like this, but because I'm not familiar with Atmel I cannot give a full answer.

@TodorSimeonov oops good catch!  I've been doing the latter -- measuring frequency -- in a current project so that's where my mind's been.  +1 to the Atmel link!

I got the feeling that PWM isn't the best "protocol" for transmitting data. Why not use UART (serial)?

@Gerben I need to implement this "protocol" because I have to drive 6 AtTiny, I know it's not so suitable, it's just a workaround

What kind of data do you need to transmit? If you just need to send a short number,  you could just send that number of pulses, with a quite period after it. Very easy to read, no ambiguous readings, as it doesn't rely on very precise timing, like PWM (where you might send 120, but read 118 on the tiny, because of inaccuracies).

@Gerben That is not a problem, I have only 8 cases to choose (I have to switch 3 leds, basically I'm doing an RGB controller), so a big accuracy is not required (I could make in the if controlling on the input pin a +/-10 error tollerance).

You don't need to read the duty cycle, just the time that the PWM signal is high. First wait for the input pin to go high, then start a timer, wait for the signal to go low again, and finally read the timer value. If other tasks need to be performed concurrently then use pin change interrupt to detect the high and low transitions.
If the ATtiny is running Arduino software then the solution is even easier - just use the pulseIn() function.
This technique works for all PWM values except 0 and 255. With these values the pin stays low or high permanently, so there are no transitions to time. The easiest way around this is to simply avoid transmitting 0 or 255.
Alternatively you could pass the PWM signal through an RC filter to produce a 'DC' voltage, then read it with the ADC. However this will slow the response time down, and the signal will produce intermediate values as it goes from one voltage to another. To get good resolution the RC filter would need to have a long time constant, and you might have to average several readings to get a stable value.

Well, thanks. I'll try this as soon as possible, it should work

It's working like a charm. I marked only now because I had to mill the board and solder everything! If someone is interested I'm documenting this "PWM controller", just contact me.

If I understood correctly you want to drive a digital output on the AtTiny45V based on the PWM value from your Arduino, right?
I would suggest to use a simple low-pass RC filter to extract the mean value from the PWM and read as an analog voltage in the AtTiny45V. As the frequency of your PWM is known, you can easily design your filter to extract the mean value of your signal.
Then, based on your PWM mean value, you can define which pin will be set.

The PWM frequency is very low - about 500Hz. The filter will have such a big R*C that he should read it analog once in a minute. Not a very good idea.

I don't think it's that big, assuming the 500Hz, set the filter to 250 Hz, choosing C = 0.1uF, then R = 6.2k, this will give a time constant of 0.0006s, so the rise time will be around 0,003s. Please, correct me if I'm wrong on this. I used this method once, but the PWM frequency was 5kHz and it was a long ago.

these values with a 5V 50% PWM at 500Hz give a triangular (sawtooth) waveform with Vmin=0.8V, Vmax=4.2V. - PSPICE simulation results, I'm not joking :) R*C needs to be much bigger.

@TodorSimeonov, You're absolutely right, I was thinking about a step input to the filter instead of a square wave. Thanks to clarify my proposition.


text:
Arduino-based mains frequency monitor follow-up
Following my
previous question, I'm getting closer to thinking about putting together this mains frequency monitor. I would just like to do a sanity check on my electronics before I order the components and the board. Please keep in mind I am not qualified in this so I have had to research how all this will work.

A and B inputs will accept power from a 16VAC 1.25A unregulated power pack.
C1 is a 1µF 25V 85°C ceramic capacitor. I guess this is mostly unnecessary as the power pack should filter any DC bias, but it won't hurt.
D1 is an IN4001 1A standard recovery diode.
R1 is a 300ohm 500V 3W resistor. The RMS power is 16VAC, which is half-wave rectified, so that's sqrt(2) * 16 = ~24V peak @ 300ohm = 80mA peak, and about 25mA on average (right?)
IC1 is a 4N28 optocoupler. It's weird, in one data sheet I see 80mA max forward current on inputs but in another I see 60mA. Anyway, the average should be 25mA so I guess that's probably going to be okay?
The Arduino I will use is the Arduino Micro, as it's quite small and also has a 16Mhz crystal oscillator that will provide a more stable clock than a ceramic resonator. The Arduino will be powered by USB, which I believe is 5V. The digital I/O pins I believe will also operate at 5V and are rated at 40mA max.
C will come from one of the Arduino's digital output pins, and D will go to the Arduino's GND.
R2 is a 150ohm 500mW 250V resistor, that should ensure the C→D current does not exceed 40mA @ 5V.
Now, assuming the components look okay and the circuit looks okay (I assume the circuit is fine), I just had some questions:

Do I need to add anything to the output of the 4N28 coming from the input? I think with a regular transistor, some of the base current gets added to the collector current?
What can I expect the response on the output of the 4N28 to look like? I assumed that it would more-or-less be a square wave, where even a tiny current on the input would activate the transistor and allow the output current to flow freely on the other side, but someone has suggested that this might not be the case?
The way it is set up, the Digital I/O pin can be "trying" to output or not, and that's basically irrelevant to what the transistor is doing. When the transistor is on, the output current from the pin will successfully flow to GND. I assume there is a way to detect this in the Arduino? Something like setting the output pin to 1 and check in loop when there is or is no current flowing?

Thank you!

3: your circuit will not work. Think pushbutton where the optocoupler is the button.

The capacitor is pointless. There can be no DC offset since there is no reference for it to be offset from. All it will do is mess with your current, screwing your power factor.

@Majenko thanks, I can remove the capacitor. I don't understand your explanation about why the circuit will not work? Or how to fix it?

You make poor assumptions about how GPIOs and transistors work. In this situation the transistor is merely a switch. Treat it as such. That means pull up resistor to VCC, and GPIO set to input mode.

Oh, and program it to use interrupts or, better, the Input Capture peripheral.

@Majenko ok so it's just a minor change: +5V goes to C, D goes to Digital I/O pin, and digital I/O pin goes to GND via a resistor? Do I also need a resistor from the D to the pin to ensure it's 40mA?

To ensure what is 40mA?

@Majenko the current from the +5V to the digital I/O pin via the opto. On the PIC, I'm pretty sure you need to put resistors from VCC to the digital inputs.

That only makes sense if the pin is an output. The only resistor you need on the pin is a pullup like a button.

@Majenko Arduinos arrived yesterday and the transformers arrived today. I got it set up and it's working great. I have 2 decimal places with micros() and I will convert to timer1 later for 3 decimal places. I wired it up differently, thought. I have the pin connected straight to ground, and the +5V going to the pin via the opto.

You should remove the capacitor. It won't remove any DC offset because there can be no DC offset. From where would the DC offset be relative? There is only two points in the circuit, and both of them are direct from the transformer and is an AC waveform. There is no concept of a DC offset in such a circuit.  All the capacitor will do is impose a phase change between the current and voltage of the AC waveform limiting the current during the conducting period of the diodes. You have a resistor for that function.
You make some incorrect assumptions about how to read the data. You talk about outputting a signal and somehow finding out if the transistor is on or not by if that signal is being output. That's completely backwards. Instead you should treat the transistor like a simple pushbutton and provide it with a pullup (or pulldown if you prefer) resistor, like this:

simulate this circuit – Schematic created using CircuitLab
You should feed the signal into an interrupt-enabled pin (such as D2 on the Uno as shown) so that an interrupt can be used for capturing the incoming edge time. Better would be to use the Input Capture peripheral, but that is harder to program for as there is no (AFAIK) library for it.
Yes, it would be possible to use the internal pullup resistor of the input pin instead of an external one, however using an external one allows you to fine tune the resistance which, coupled with the gate capacitance of the input pin, forms a low-pass filter limiting the frequency range you can monitor. At 50Hz it shouldn't be a problem though, so the choice is yours. Personally I use an external one.


text:
Serial data affected by interrupt
In my recent project, I have done everything means capture serial data and split it out in proper form.
Until now everything is fine. But when I add another portion of code which contains Interrupt. Now, whenever Interrupt come into the picture, my incoming serial data totally destroy. And when I remove that interrupt portion then everything is fine. But this interrupt is also given one my reading(RPM READING).
I tried out detachinterrupt function, it disables my interrupt then I can't get my RPM READING.
I also tried out interrupts() and noInterrupts() function. But I don't get any results. I think I'm not able to utilize my code with this function.
Here, below my whole code which is a little bit lengthy. But, it's necessary.
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String data_TPS_Json = "";
String data_MAP_Json = "";
String data_LOAD_TM_Json = "";

String data_LOAD_RI_Json = "";
String data_RPM_Json = "";
String data_INJECTION_TIME_Json = "";

String response = "";
bool begin = false;

char in;
int len = 0;

float TPS_Json;
float MAP_Json;
float LOAD_TM_Json;

float LOAD_RI_Json;
float RPM_Json;
float INJECTION_TIME_Json;

//----------------------------For MAP calculation----------------------------//
float MAP_MIN = 0.85;
float MAP_MAX = 1.90;

int LOAD_MIN_MAP[] = {1, 2};
int LOAD_MAX_MAP[] = {3, 4};

float mMAP[2] = {};
float yMAP[2] = {};

int i, j, a;
float MAP, mFinalMAP, yFinalMAP;

//----------------------------For TPS calculation----------------------------//
float TPS_MIN = 0.00;
float TPS_MAX = 5.00;

int LOAD_MIN_TPS[] = {1, 3};
int LOAD_MAX_TPS[] = {2, 4};

float mTPS[2] = {};
float yTPS[2] = {};

int k, l, b;
float TPS, mFinalTPS, yFinalTPS;

//----------------------------For LOAD calculation---------------------------//
int LOAD_MIN = 2;
int LOAD_MAX = 100;

float injTime_MIN_LOAD[] = {6.20, 6.26};
float injTime_MAX_LOAD[] = {7.80, 8.06};

float mLOAD[2] = {};
float yLOAD[2] = {};

int m, n, c;
float LOAD, mFinalLOAD, yFinalLOAD;

//----------------------------For RPM calculation----------------------------//
const int kPinRPM = 3;        // RPM / Digital Pin 3
const int RPMInterrupt = 1;   // RPM's interrrupt pin
byte engineCylinders = 2;         // Engine cylinders = 4;
byte engineCycles = 4;            // Engine cycle = 2
int refreshInterval = 750;        // Milliseconds between sensor updates
unsigned long previousMillis = 0;
volatile int RPMpulses = 0,  RPM0 = 0;
int RPM, Final_RPM;

int RPM_MIN = 400;
int RPM_MAX = 6000;

float injTime_MIN_RPM[] = {6.20, 7.80};
float injTime_MAX_RPM[] = {6.26, 8.06};

float mRPM[2] = {};
float yRPM[2] = {};

int o, p, d;
float mFinalRPM, yFinalRPM;

//------------------------For GAS PRESSURE calculation-----------------------//
float minPosVolGas = 0.00;
float maxPosVolGas = 2.50;

float minInjPerPos = 0.35;
float maxInjPerPos = 0.00;

float minNagVolGas = 2.50;
float maxNagVolGas = 5.00;

float minInjPerNag = 0.00;
float maxInjPerNag = 0.25;

float GAS_Pressure, mGasPos, mGasNag, yGasPos, yGasNag;

//----------------------For INJECTION TIME calculation-----------------------//
float yInjTime, injTime, gasInjTime;
volatile uint32_t kInjTime = 0;

const int kPinInj = 8;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);

  pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
  attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

  pinMode(kPinInj, OUTPUT);
}

void loop()
{
  //----------------------------MAP----------------------------//

  MAP = analogRead(A0) * (5.0 / 1023.0);

  for(a = 0; a < 2; a++)
  {
    mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
    yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
  }

  //----------------------------TPS----------------------------//

  TPS = analogRead(A1) * (5.0 / 1023.0);

  for(b = 0; b < 2; b++)
  {
    mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
    yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
  }

  //----------------TPS/MAP CALLIBRATION / LOAD----------------//

  mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
  yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

  mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
  yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

  LOAD = (yFinalTPS + yFinalMAP) / 2;

  //----------------------------LOAD---------------------------//

  for(c = 0; c < 2; c++)
  {
    mLOAD[m] = (injTime_MAX_LOAD[c] - injTime_MIN_LOAD[c]) / (LOAD_MAX - LOAD_MIN);
    yLOAD[n] = mLOAD[m] * (LOAD - LOAD_MIN) + injTime_MIN_LOAD[c];
  }

  //----------------------------RPM----------------------------//

  if(millis() - previousMillis > refreshInterval)
  {
    previousMillis = millis();
    RPM =  getRPM();
  }

  for(d = 0; d < 2; d++)
  {
    mRPM[o] = (injTime_MAX_RPM[d] - injTime_MIN_RPM[d]) / (RPM_MAX - RPM_MIN);
    yRPM[p] = mRPM[o] * (RPM - RPM_MIN) + injTime_MIN_RPM[d];
  }

  //-----------LOAD/RPM CALLIBRATION / INJECTION TIME----------//

  mFinalLOAD = (yRPM[1] - yRPM[0]) / (LOAD_MAX - LOAD_MIN);
  yFinalLOAD = mFinalLOAD * (LOAD - LOAD_MIN) + yRPM[0];

  mFinalRPM = (yLOAD[1] - yLOAD[0]) / (RPM_MAX - RPM_MIN);
  yFinalRPM = mFinalRPM * (RPM - RPM_MIN) + yLOAD[0];

  yInjTime = (yFinalLOAD + yFinalRPM) / 2;
  injTime = (yInjTime * 1000) / 1000;

  //------------------JSON SERIAL DATA---------------------//

  while(Serial.available() || !begin)
  {
      in = Serial.read();

      if (in == '{')
      {
        begin = true;
      }

      if(begin)
      {
        response += (in);
      }

      if(in == '}')
      {
        break;
      }

      delay(1);
  }

  len = response.length();

  if(len == 39)
  {
    data_TPS_Json = response.substring(8, 12);
    data_MAP_Json = response.substring(21, 25);
    data_LOAD_TM_Json = response.substring(35, 37);

    jsonMapTps();
  }

  if(len == 52)
  {
    data_LOAD_RI_Json = response.substring(9, 13);
    data_RPM_Json = response.substring(22, 26);
    data_INJECTION_TIME_Json = response.substring(46, 50);

    jsonRpmLoad();
  }

  //------------------------GAS_PRESSURE-----------------------//

  GAS_Pressure =  analogRead(A2) * (5.0 / 1023.0);

  mGasPos = (maxInjPerPos - minInjPerPos) / (maxPosVolGas - minPosVolGas);
  yGasPos = mGasPos * (GAS_Pressure - minPosVolGas) + minInjPerPos;

  mGasNag = (maxInjPerNag - minInjPerNag) / (maxNagVolGas - minNagVolGas);
  yGasNag = mGasNag * (GAS_Pressure - minNagVolGas) + minInjPerNag;

  if(GAS_Pressure >= 0.00 && GAS_Pressure < 2.50)
  {
    gasInjTime = injTime + (injTime * yGasPos);
  }
  else if(GAS_Pressure >= 2.50 && GAS_Pressure <= 5.00)
  {
    gasInjTime = injTime - (injTime * yGasNag);
  }

  //--------------------Pulse Generation-----------------------//

  if((kInjTime > 0) && ((millis() - kInjTime) >= injTime))
  {
    kInjTime = 0;
    digitalWrite(kPinInj, 0);
  }
}

void countRPM()
{
  RPMpulses++;

  digitalWrite(kPinInj, RPMpulses & 1); // Set or clear kPinInj
  if(RPMpulses & 1)
  kInjTime = millis();  // Store alternate times
}

int getRPM()
{
  Final_RPM = ((RPMpulses * (60000UL / 2) * (engineCycles/engineCylinders)) / refreshInterval);
  RPM0 = RPMpulses &= 1;
  RPMpulses - RPM0;
  return Final_RPM;
}

void jsonMapTps()
{
    TPS_Json = data_TPS_Json.toFloat();
    MAP_Json = data_MAP_Json.toFloat();
    LOAD_TM_Json = data_LOAD_TM_Json.toFloat();

    lcd.setCursor(0, 0);
    lcd.print(TPS_Json);
    lcd.setCursor(8, 0);
    lcd.print(MAP_Json);
    lcd.setCursor(0, 1);
    lcd.print(LOAD_TM_Json);
}

void jsonRpmLoad()
{
    LOAD_RI_Json = data_LOAD_RI_Json.toFloat();
    RPM_Json = data_RPM_Json.toFloat();
    INJECTION_TIME_Json = data_INJECTION_TIME_Json.toFloat();

    lcd.setCursor(0, 0);
    lcd.print(LOAD_RI_Json);
    lcd.setCursor(8, 0);
    lcd.print(RPM_Json);
    lcd.setCursor(0, 1);
    lcd.print(INJECTION_TIME_Json);
}

Please add memory statistics.

You haven't specified what hardware you are using.  You need to narrow down the fault. "My data gets destroyed" is not very helpful.  What does you program read when you get an interrupt, how does this vary to normal?  With that number of Strings in memory I agree with @MikaelPatel it is probably memory related.

@MikaelPatel means how many bytes consume by code?

@CodeGorilla Hardware means Arduino Uno or Arduino Mega? Then I used here Arduino Mega. OK... So I have to give a full flow of what I want to do and what happens. Am I right?

Your interrupt handler is short and simple. It should definitely not disturb your program. It does, however, increase memory usage (stack space), which could be the cause of your problems. You should definitely follow Jot's advice about making most variables local and getting rid of String objects.

Finally got the solution. My method of capturing Serial string data is a little bit faulty. And also remove maximum strings and try to declare maximum local variables And use ArduinoJson library for parsing the data.
This is my modified code:
#include<LiquidCrystal.h>
#include <ArduinoJson.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false, finished;

//----------------------------For MAP calculation----------------------------//
float MAP_MIN = 0.85;
float MAP_MAX = 1.90;

int LOAD_MIN_MAP[] = {1, 2};
int LOAD_MAX_MAP[] = {3, 4};

float mMAP[2] = {};
float yMAP[2] = {};

int i, j, a;
float MAP, mFinalMAP, yFinalMAP;

//----------------------------For TPS calculation----------------------------//
float TPS_MIN = 0.00;
float TPS_MAX = 5.00;

int LOAD_MIN_TPS[] = {1, 3};
int LOAD_MAX_TPS[] = {2, 4};

float mTPS[2] = {};
float yTPS[2] = {};

int k, l, b;
float TPS, mFinalTPS, yFinalTPS;

//----------------------------For LOAD calculation---------------------------//
int LOAD_MIN = 2;
int LOAD_MAX = 100;

float injTime_MIN_LOAD[] = {6.20, 6.26};
float injTime_MAX_LOAD[] = {7.80, 8.06};

float mLOAD[2] = {};
float yLOAD[2] = {};

int m, n, c;
float LOAD, mFinalLOAD, yFinalLOAD;

//----------------------------For RPM calculation----------------------------//
const int kPinRPM = 3;        // RPM / Digital Pin 3
const int RPMInterrupt = 1;   // RPM's interrrupt pin
byte engineCylinders = 2;         // Engine cylinders = 4;
byte engineCycles = 4;            // Engine cycle = 2
int refreshInterval = 750;        // Milliseconds between sensor updates
unsigned long previousMillis = 0;
volatile int RPMpulses = 0,  RPM0 = 0;
int RPM, Final_RPM;

int RPM_MIN = 400;
int RPM_MAX = 6000;

float injTime_MIN_RPM[] = {6.20, 7.80};
float injTime_MAX_RPM[] = {6.26, 8.06};

float mRPM[2] = {};
float yRPM[2] = {};

int o, p, d;
float mFinalRPM, yFinalRPM;

//------------------------For GAS PRESSURE calculation-----------------------//
float minPosVolGas = 0.00;
float maxPosVolGas = 2.50;

float minInjPerPos = 0.35;
float maxInjPerPos = 0.00;

float minNagVolGas = 2.50;
float maxNagVolGas = 5.00;

float minInjPerNag = 0.00;
float maxInjPerNag = 0.25;

float GAS_Pressure, mGasPos, mGasNag, yGasPos, yGasNag;

//----------------------For INJECTION TIME calculation-----------------------//
float yInjTime, injTime, gasInjTime;
volatile uint32_t kInjTime = 0;

const int kPinInj = 8;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);

  pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
  attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

  pinMode(kPinInj, OUTPUT);
}

void loop()
{
  //----------------------------MAP----------------------------//

  MAP = analogRead(A0) * (5.0 / 1023.0);

  for(a = 0; a < 2; a++)
  {
    mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
    yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
  }

  //----------------------------TPS----------------------------//

  TPS = analogRead(A1) * (5.0 / 1023.0);

  for(b = 0; b < 2; b++)
  {
    mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
    yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
  }

  //----------------TPS/MAP CALLIBRATION / LOAD----------------//

  mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
  yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

  mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
  yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

  LOAD = (yFinalTPS + yFinalMAP) / 2;

  //----------------------------LOAD---------------------------//

  for(c = 0; c < 2; c++)
  {
    mLOAD[m] = (injTime_MAX_LOAD[c] - injTime_MIN_LOAD[c]) / (LOAD_MAX - LOAD_MIN);
    yLOAD[n] = mLOAD[m] * (LOAD - LOAD_MIN) + injTime_MIN_LOAD[c];
  }

  //----------------------------RPM----------------------------//

  if(millis() - previousMillis > refreshInterval)
  {
    previousMillis = millis();
    RPM =  getRPM();
  }

  for(d = 0; d < 2; d++)
  {
    mRPM[o] = (injTime_MAX_RPM[d] - injTime_MIN_RPM[d]) / (RPM_MAX - RPM_MIN);
    yRPM[p] = mRPM[o] * (RPM - RPM_MIN) + injTime_MIN_RPM[d];
  }

  //-----------LOAD/RPM CALLIBRATION / INJECTION TIME----------//

  mFinalLOAD = (yRPM[1] - yRPM[0]) / (LOAD_MAX - LOAD_MIN);
  yFinalLOAD = mFinalLOAD * (LOAD - LOAD_MIN) + yRPM[0];

  mFinalRPM = (yLOAD[1] - yLOAD[0]) / (RPM_MAX - RPM_MIN);
  yFinalRPM = mFinalRPM * (RPM - RPM_MIN) + yLOAD[0];

  yInjTime = (yFinalLOAD + yFinalRPM) / 2;
  injTime = (yInjTime * 1000) / 1000;

  //------------------JSON SERIAL DATA---------------------//

  StaticJsonBuffer<100> jsonBuffer;

  while (finished == false)
  {
    if (Serial.available())
    {
      const char in = Serial.read();
      if (in == '{')
      {
        response = "";  // Blank the string
        begin = true;
      }
      if (begin)
      {
        response += (in); // Only write if within the {}
      }
      if (in == '}')
      {
        begin = false;   // Prevent any chars between } and { leaking through.
        break;
      }
    }
    delay(1);
  }

  JsonObject& root = jsonBuffer.parseObject(response);

  const char* ActionOne = root["ActionOne"];
  const char* ActionTwo = root["ActionTwo"];

  //--------------------TPS/MAP/LOAD-----------------------//

  if(root.containsKey("ActionOne"))
  {
    float TPS = root["TPS"];
    float MAP = root["MAP"];
    int LOAD = root["LOAD"];

    lcd.setCursor(0, 0);
    lcd.print(TPS);

    lcd.setCursor(8, 0);
    lcd.print(MAP);

    lcd.setCursor(0, 1);
    lcd.print(LOAD);
  }

 //--------------LOAD/RPM/INJECTION_TIME-------------------//

  if(root.containsKey("ActionTwo"))
  {
    float LOAD = root["LOAD"];
    int RPM = root["RPM"];
    float INJECTION_TIME = root["INJECTION_TIME"];

    lcd.setCursor(0, 0);
    lcd.print(LOAD);

    lcd.setCursor(8, 0);
    lcd.print(RPM);

    lcd.setCursor(0, 1);
    lcd.print(INJECTION_TIME);
  }

  //------------------------GAS_PRESSURE-----------------------//

  GAS_Pressure =  analogRead(A2) * (5.0 / 1023.0);

  mGasPos = (maxInjPerPos - minInjPerPos) / (maxPosVolGas - minPosVolGas);
  yGasPos = mGasPos * (GAS_Pressure - minPosVolGas) + minInjPerPos;

  mGasNag = (maxInjPerNag - minInjPerNag) / (maxNagVolGas - minNagVolGas);
  yGasNag = mGasNag * (GAS_Pressure - minNagVolGas) + minInjPerNag;

  if(GAS_Pressure >= 0.00 && GAS_Pressure < 2.50)
  {
    gasInjTime = injTime + (injTime * yGasPos);
  }
  else if(GAS_Pressure >= 2.50 && GAS_Pressure <= 5.00)
  {
    gasInjTime = injTime - (injTime * yGasNag);
  }

  //--------------------Pulse Generation-----------------------//

  if((kInjTime > 0) && ((millis() - kInjTime) >= injTime))
  {
    kInjTime = 0;
    digitalWrite(kPinInj, 0);
  }
}

void countRPM()
{
  RPMpulses++;

  digitalWrite(kPinInj, RPMpulses & 1); // Set or clear kPinInj
  if(RPMpulses & 1)
  kInjTime = millis();  // Store alternate times
}

int getRPM()
{
  Final_RPM = ((RPMpulses * (60000UL / 2) * (engineCycles/engineCylinders)) / refreshInterval);
  RPM0 = RPMpulses &= 1;
  RPMpulses - RPM0;
  return Final_RPM;
}

I'm also trying to capture response as char array but not able to capture it. Please guide me about that otherwise this one string may not cause any heap fragmentation. I am so glad if someone helps me out for this.

You need to clean up the whole sketch. I will try to mention the most important things first.
For an Arduino Uno, this sketch uses 520 bytes RAM and 1528 bytes are free to use for stack and heap. That seems enough but with heap fragmentation it might be a problem, see: Adafruit about an increasing heap
The data_... Strings are only to display something. They can be replaced with normal strings. You could also make a single buffer of a char array for the "response".
The variables that are used in the interrupt routine and also outside the interupt routine should be made volatile.
When the variable begin is false, you still read data with Serial.read(). That can't be right. Could you rewrite that part ?
The variable kInjTime is used to store the millis() time and also to disable it by setting it to zero. That is not good programming since millis() can be zero. It is better to add an extra variable to turn that timing on and off.
The use of digitalPinToInterrupt() is advised when using attachInterrupt(). That makes it easier to see which pins are used.
The function digitalWrite() takes HIGH or LOW, not 0 or 1 and not a bit of a variable, only HIGH or LOW.
Try to use more local variables. You have too many variables as global, which makes it hard to read the sketch.

Oh...Thank you for this points that you mentioned. Let me explain every point.

"data_" strings are displaying the value of data. Suppose serially data {"TPS":"0.40","MAP":"0.95","LOAD":"14"} comes. Then that "data_" strings hold 0.40, 0.95 &  14.

Ok.. Means I have to initialize all that variable made volatile which I used in the Interrupt routine.

Ok, that "Serial.read" portion is capture serial data. Ok, I can try to rewrite that portion.

Ok, means I have to use another variable which holds 0 or 1?

digitalPinToInterrupt ... Ok, that thing I keep in my mind.

But 1 or 0 perform same things as HIGH or LOW do...

Ok, using local variable some time it gives error like variable is not declared in this scope . So, I made all variables global.

LOW and HIGH is 0 and 1, but it is better to make good readable code, than trying to write weird code. Without String objects, the sscanf can be used to split the serial data. The strtok function could be used as well. Or even using array indexes and making the strings zero-terminated is also possible. You could add a boolean variable next to kInjTime. For example: boolean kInjTimeEnable = false; I think the 'a', 'b', 'c', 'd' are local variables, you can declare those inside the for-statement: for ( int a = 0; a < 2..... and there are more variables that are only used locally.


text:
timer0_millis always returns 0
I am trying to make a simple debounce function as explained here but the condition if((millis()-timeCheck)>reboundDelay) is never met.
As you can see in my code below, I am trying to control a PWM with two push buttons. I am currently sending it on a LED.
With AS7 and vMicro I put some breakpoints and realized that timeCheck was stuck at 0 and was an unsigned int instead of the unsigned long I declared. With the debugger I looked inside of the millis() function and saw that timer0_millis wasn't increasing neither, stuck at 0.
Here is my short code (it's a sketch, it can surely be rewritten in a more efficient way) :
int PWM=9;
int dutyP=2;
int dutyM=3;
int duty=123;
bool stateP=0;
bool stateM=0;
bool prevStateP=0;
bool prevStateM=0;
unsigned long reboundDelay=500;
unsigned long timeCheck=millis();

void setup() {
  pinMode(PWM,OUTPUT);
  pinMode(dutyP,INPUT);
  pinMode(dutyM,INPUT);
}

void loop() {
  stateP=digitalRead(dutyP);
  stateM=digitalRead(dutyM);
  if(stateP != prevStateP || stateM != prevStateM) {
    timeCheck=millis();
  }
  if((millis() -  timeCheck) > reboundDelay) {
    if(stateP==1) {
      duty=duty+25;
    } else if(stateM==1) {
      duty=duty-25;
    }
    analogWrite(PWM,duty);
    prevStateP=stateP;
    prevStateM=stateM;
  }
}

And finally, the strange part. When I upload it on my Genuino Uno for like 30 seconds, the pushbuttons do nothing (it may be that the if works) and afterwards I can increase and decrease the duty cycle but without the delay that the condition should bring (the LED flashes really fast due to an overflow in analogWrite).
Any help is welcomed, the strange part is secondary to me but I would really like to make millis() work properly.

bool variables have two possible values true and false.  1 and 0 are technically ints, you might be OK but I wouldn't do it.  You should also check for wrap on duty.

Would it be possible to just do this loop?  loop(){Serial.println(millis());delay(500);} If you are right about millis not moving then this will prove it.  There may be something in the debuggers that interfere with millis.

I tried to but nothing happen in the serial monitor despite :
Port closed
Uploading to I/O board
Opening port
Port open

Should I write stateP==true or false instead of 1 or 0 ?

Did you try with an empty project?  If so you have a bigger problem :(

true == 1 false == 0, yes

Trying in a new project right away.

Do this on an Arduino Uno / Atmel ATmega328P.   There are many different kinds of Arduino boards with many processors.  They all do not work perfectly with respect to their boot loader software and SDK implemtations.  Also, I would not define the type and call a method to assign a value to the type outside of a method.  I would define "timeCheck" then assign it a value within the methods.

Sorry for the wait AS7 crashed... I made a new projet just inserted your lines in the loop function and started debugger on the .ino file... and it worked. Didn't I had to add the .cpp file before I could debug ? Anyway, there is still no sign of millis in the serial monitor.

@st2000 I didn't understood what you meant in the first part of your comment, should I configure something in a certain way ? I am using an genuino uno rev3 with an ATMega328P.
For the second part, the unsigned long timeCheck=millis(); it was a wild try, I forgot to clean it up before posting here. Thank you.

I tried in multiple ways, Serial.println() doesn't work at all. I might as well install AS6.2 and see if it works better.

There are many types of Arduinos.   And many use totally different processors.  The SDKs and Arduino boot loader quality for some are questionable.  You did not specify your Arduino HW.  And now-a-days, because of this problem, that is important.  But I see you are using an ATMega328P.  The same processor that is on a real Arduino Uno.  So if there is special hardware used to run the timer is should work.  I would next suggest trying one of the short example mills programs found at the official Arduino site.  Then work back to your program from there.

I think there is just a logic error that doesn't immediately jump out: When the button state is changed, it will always set timeCheck equal to millis(). For instance, as long as you are pressing "P", stateP will not be equal to prevStateP and so "timeCheck=millis()" will executed everytime thru the loop, so the difference will never reach 500.
if(stateP != prevStateP || stateM != prevStateM){
    timeCheck=millis();
}

Should be something like:
if(stateP == prevStateP && stateM == prevStateM){
    timeCheck = millis();
}

This will continually keep timeCheck = millis() until either button is pressed. Once the button is pressed, timeCheck will remain at the value of millis() read just before the press, until the debounce value is reached (unless noise/bounce and not a real press, or button is released early as 500ms is a relatively long time).
This is probably the simplest modification to the code I can come up with. Hope it helps.

I would suggest a few things:
1) comment on your code -> lay out the basic logic so that you and others can help you debug it;
2) use brackets liberally -> don't rely on memory (=faulty) on the order of operations. instead, define it explicitly;
3) check your logic -> make sure that your code does what you want it to do;
4) pay attention to data type: 8-bit vs. 16-bit, etc.
5) modularize your code -> this allows more efficient debugging and code reusing.
for example, your code can be simply described as
  button_state = read_button(); //read button state, with debouncing
  if (button_state = BUTTON_UP) pwminc_dc(pwm_dc); //increase duty cycle, with boundary checking
  if (button_state = BUTTON_DOWN) pwmdec_dc(pwm_dc); //decrement duty cycle, with boundary checking

with the code modularized, you just need to worry about getting individual pieces right.


text:
Avr dude programmer
I was trying to upload a hex file to my attiny85 with an arduino,and I came across this:
avrdude -c avrisp (followed by other codes and the flash address )

This doesn't work and it gave one of the most famous arduino errors : stk500_getsync() : not in sync: resp=0x00
Then I tried
   avrdude -c arduino

And the code was successfully downloaded, but the chip itself doesn't work as intended. So this is the question, what does the -c [programmer id] actually do, for example in this case, does it download the hex file to my arduino?
Thanks in advance.

DId you disable the reset on the Arduino after installing the ArduinoISP sketch? If not, then you just reprogrammed the Arduino with your ATTiny85 program.

@Majenko disable with capacitor at the reset? I just tried and same error code with avrisp.(Also I don't know if I actually prevented the reset or not, no way I know now.) So the arduino option programs the arduino regardless of what chip I choose later ?

The -c selects which protocol to use to talk to the remote device. -c arduino selects the Arduino's bootloader as the protocol to use. -c avrisp selects the protocol spoken by the ArduinoISP sketch.

Did you reprogram the ArduinoISP sketch back on the Arduino after breaking it with -c arduino and before testing it again with the reset disabled?

@Majenko the one in the example , yes. I also reburned the bootloader for the attiny85 just in case . Since the data flows from my laptop through the arduino then into the attiny85, does this mean that by selecting -c arduino will download the hex file into the arduino, or download the hex file into the attiny85 with arduino protocol ?

It sounds like you're not actually doing what you describe (and we assume from the situation) you are doing. Using an Arduino to program an ATTiny85 usually means using it as an ISP to flash the chip directly. Instead it sounds like you are actually using a bootloader on the ATTiny and using the Arduino as a dumb UART interface. Is that correct?

@Majenko that... Actually sounds like it. All I want is to download my hex file into my attiny85 , and I do not have any other way of connecting the attiny85 to my laptop.

Yet you seem to have the ability to program the bootloader on the ATTiny? Why not just program the HEX file directly using the same method instead of messing with bootloaders?

@Majenko I burned the bootloader with the arduino software.(under the tools) I really do not have the ability to properly program an avr device now. And I think I'm not actually burning the bootloader although it says so, as I saw from other forums that I am just actually resetting the clock rate of the chip.

@Majenko I couldn't use "avrisp" because of the error, and "arduino" doesn't seem to work.

Using an Arduino to program a microcontroller is very crude at best. You should invest in a USBASP from eBay. They're dirt cheap.

Which bootloader do you think you are installing on the ATTiny?

@Majenko because of where I live, it's not that easy to obtain these products, eBay included. And this is my one time project, and I won't be returning to avr devices anytime soon (I think).

@Majenko bootloader wise..... I have no idea. Attiny85 comes with a bootloader...Right?

You have no idea what bootloader you tried installing? Where did you get it?

@Majenko here http://my.element14.com/microchip/attiny85-20pu/mcu-8bit-attiny-20mhz-dip-8/dp/1455162?CMP=i-55c5-00001621

No, I mean the bootloader. Where did you get the bootloader? I also reburned the bootloader for the attiny85 just in case

@Majenko the "burn bootloader" under the "tools" in the arduino ide. Which most likely isn't a bootloader.

Try these steps:

Install ArduinoISP (in the examples menu) on your Arduino board.
Disable reset on the Arduino board by adding a 10µF capacitor between the RESET and GND pins.
Wire the ATTiny chip to the Arduino following this schematic.
Run the upload command using -c avrisp with your program's HEX file

Alternatively you can just install the boards package detailed in the schematic link and program it directly from the Arduino IDE instead of messing with the avrdude upload command.
You must also ensure that you are uploading at the right baud rate. The ArduinoISP sketch defaults to 19200 baud:
// Configure the baud rate:

#define BAUDRATE    19200
// #define BAUDRATE 115200
// #define BAUDRATE 1000000

and you must match that in your avrdude command with, for example, -b 19200.

C:\Users\User>avrdude -c avrisp -P com1 -p t85 -Uflash:w:C:\Users\User\Desktop\sd8p_mo.hex:i
avrdude: stk500_getsync(): not in sync: resp=0x00
avrdude done.  Thank you. (exact code and error returned. also using 22uF capacitor, other forum said it was okay)

I would suggest you forget using the command line for this. Follow the tutorial I linked to step by step and use the IDE for everything.

Oh, and is your Arduino really on COM1?

it is. I changed it in the device manager and made sure of it in the arduino ide. The code I want to import is found in hex.(http://elm-chan.org/works/sd8p/report.html), and the tutorial only allows ide, if im right.

There is source there, just not for the Arduino IDE (or not easily).

Add -b 19200 to the avrdude command.

You can also try -c arduinoisp

Another one to try is -c stk500v1. It's really confusing - they have "ArduinoISP", "ArduinoISPOrg" and "ArduinoAsISP" - all to do the same thing and all slightly different. I guess for different versions of the ArduinoISP code.

HOLY It worked!!! the "-b 19200"!!!! Thank you so much !!!! I know what it means (baudrate right), but why?

The baud rate has to match the baud rate programmed in the ArduinoISP sketch. That defaults to 19200, but avrdude defaults to 115200.

Let us continue this discussion in chat.


text:
Can't get 4 digit 7 segment display to show different values
I'm an Arduino newbie having problems getting a 4 digit 7 segment display to work. The display is connected to a 74HC595 and the setup is from the elegoo tutorial 28 (I think it is download only).
I figured how to control which number to display, but all 4 digits always share the same number, so it is always like 1111, 5555, 9999 etc.
I've heard about something called multiplexing which might do the trick, but I can't adapt it to my project yet, missing too much experience.
This is the code that toggles between 2222 and 8888.
I want to be able to display any number like 1234 though.
Any help is very appreciated.
int latch=9;  //74HC595  pin 9 STCP
int clock=10; //74HC595  pin 10 SHCP
int data=8;   //74HC595  pin 8 DS

void setup()
{
  pinMode(latch,OUTPUT);
  pinMode(clock,OUTPUT);
  pinMode(data,OUTPUT);
}

void Display(unsigned int num)
{
  digitalWrite(latch,LOW);
  shiftOut(data,clock,MSBFIRST,num);
  digitalWrite(latch,HIGH);
}

void loop()
{
    Display(91);
    delay(1000);
    Display(127);
    delay(1000);
}

We have no clue what elegoo is. Show us your circuit.

Either you need multiplxing or you'll need to daisy chain 4 74HC595, one per digit. Otherwise, you won't get anything different than now. For multiplexing, I think there have been plenty of questions about this topic already. And a google search will show you what you need.

Hello my sevensegment have 14 pin can you send schematic map????

You have a common cathode display and all your cathodes are tied to ground through resistors. You have no way at all of separating out the different digits.
You cannot directly drive such a display with a shift register like that - you need a more direct connection to the Arduino (it needs to be high speed) and rapidly switch each cathode on and off in sequence to display each of the four numbers one after another.
Also the resistors should be in the 8 anodes, not the 4 cathodes.

Thank you Majenko for taking the time. I guess that means that this tutorial setup is not recommended nor feasible to be used to drive all digits separately then.
I will have to search for a different setup that I can take as the base then.

It is possible to use the shift register if you also connect the cathodes to the Arduino and select each one in turn. With the shift register though it may be flickery. The code is also much more complex than just shifting out a number.

https://playground.arduino.cc/Main/SevenSegmentLibrary

but all 4 digits always share the same number, so it is always like 1111, 5555, 9999 etc.

because that's how this particular circuit is designed for.

I've heard about something called multiplexing which might do the trick, but I can't adapt it to my project yet, missing too much experience.

multiplexing is no different than displaying each digit quickly (as you are doing now), and then display the next digit quickly, ....
what you are doing now will contribute to your learning multiplexing.

The problem with this setup is the circuit.
The Master Reset Pin 10 on the 595 is floating.
Use a 10K resistor to pull it up to VCC (+5V) and it will work.
I was getting all sorts of odd characters until I checked out the data sheet on the 595.

That circuit needs a 0.1uF cap from '595 VCC to Gnd for consistent operation. Ideally a resistor between each '595 output and the anode pin, and a transistor or other higher current device able to sink the current from 8 anodes being driven at once (i.e. ULN2003).  Once the cathodes can be driven seperately, to allow each digit to be selected individually, than an array can be used to map the digit to be displayed to the segments in a display:
// add before setup()
byte fontArray[] = {
0b00111111, // 0  where the bits represent dp-g-f-e-d-c-b-a
0b00000110, // 1  and 1 = segment turned on
0b01011011, // 2
// etc.
};

// and change this line in display() to display a number

shiftOut(data,clock,MSBFIRST,fontArray[num); // looks up mapping from above

// then turn on a cathode to display it for 2-3mS, then back off, and send
// out the info for the next digit


text:
Arduino % symbol meaning
I dont know what meaning of this symbol - %.
for example,
buttonPressCount % numberOfLED == i
I hope anyone can tell me the name and basic function of this symbol.

I don't understand why this question was modded down so I gave it a point.

It is called the modulus operator, and it performs the modulo operation.
TL;CBR: It results in the remainder after division is performed.

It is also in the online Arduino reference: https://www.arduino.cc/en/reference/modulo


text:
Use Female USB Type A as Power Supply for external device
I bought a female USB Type A Breakout, like this (https://www.sparkfun.com/products/12700). I thought I could use this one to simply power a USB 5v water pump. Therefore I use an external USB power supply that is regulated by a relay, that I regulate with my Arduino. But I'm wondering if it is possible to get that USB Breakout to "give out" power to my water pump.

Yes. Just connect VCC to +5V and GND to GND and you can plug a 5V device into it.
If you need to use it as a charge port (for charging a phone) you will need to connect the D+ and D- pins together.

I thought that too, but it's not working. Whats the difference between a charge port and my case?

A charge port tells the device how much current it can supply. A dumb device like a pump won't need it.

But do you have an idea, why it's not working? I use a FTDI USB plug, that I stick into a USB  Power Adaptor(with direct link to usb pump works). Then I connect VCC and GND to the usb female breakout.

ok simple as it is sometimes... there was a bad manufactoring soldier. i fixed it and now its running. thanks a lot!


text:
CJMCU-116 9DOF mpu9250 driver

I've recently bought a CJMCU-116 sensor equipped with MPU9250. It features magnetometer, accelerometer and gyroscope. It uses I2C for communication.
I've scouted everywhere but I could not find any library to make it work properly, just one that seems to work but I'm not 100% sure.
Can someone point me to the right direction, please?
 I'm using this library
found here. I know this is not the same sensor but the chip is the same, so it should work, am I right?

"Seems to work" but you're not sure...? Either it works or it doesn't. Which is it?

It reads values but sometimes suddenly stop working, even though everything is connected. I've updated the question with the links to the libraries.

The make and model number of the sensor is of no importance. It's just a PCB to hold the chip and power circuitry. Maybe it's your wiring. I2C can be iffy and lock up with loose connections.

So it's enough to get a driver for the MPU9250 regardless the sensor?

Yep. It's the chip you're communicating with, not the board.

Well, I suppose this would be of great help, thank you, I'll keep you posted!

If you use a 5V Arduino board without level shifter for the I2C, then the MPU-9250 might have been damaged by now. The Sparkfun library was the first thing that came to my mind. You can use that library. How long are the I2C wires ? what kind of cable do you use for I2C ? Use seperate wires without cable and a maximum of 50 cm for the I2C.

I'm using 20cm jumper wires male/female and I'm powering the sensor with 3.3v. Why do you think it could have been damaged?

I'm voting to close this question as off-topic because it seeks to find an external resource in the form of a library.