text:
Using micros() to measure analogRead() time varies based on Serial.print location?
I'm trying to use micros() to measure the time it takes to execute an analogRead() cycle, but am having some issues.  Originally, I just printed out the measured time for the analogRead() right after doing the subtraction, but I wanted to change that to printing out all of the time values for the 100 loops at once.  When I print the start times, end times, and values both in the if statement (right after calculating them) and at the end, the values printed are the same.  I'm not sure if they're accurate because they fluctuate a lot within those 100 tests.  For example, some of these measured times consecutively are 216, 97, 153, 34, 89, 145, 27.  I put the ADC in freerun mode, so I figured it could be normal for that.  However, when I don't print the start times, end times, or values immediately after calculating them and instead try to print them in the else if statement, it gives a stream of values that are all either 407 or 408.  If I print "Test" instead of the values right after calculating them, it still gives the (I'm assuming) correct values that vary a lot, not the 407s.  If, instead of printing them in the if statement, I print them just in the general loop (currently commented out) and the else if statement, they are still the varying maybe-correct values.  I assumed that even if the values aren't being printed, they're still being stored in the array correctly.  I don't understand why printing something unrelated right after storing the values would change them.  Any ideas?
Thanks
    int sensorPin = A1;    // select the input pin for the potentiometer
    int ledPin = 13;      // select the pin for the LED
    int sensorValue[1000];  // variable to store the value coming from the sensor
    int ind = 0;
    int starts[1000];
    int ends[1000];
    int vals[1000];
    int stopprint = 0;
    int i = 0;
    int countto = 100;

    void setup() {
      // declare the ledPin as an OUTPUT:
      Serial.begin(57600);
      analogReadResolution(12);
      pinMode(ledPin, OUTPUT);
      Serial.println("ready to begin");
        analogReadSetup(A1);
      for (i = 0; i < 1000; i++) {
        starts[i] = 0;
        ends[i] = 0;
        vals[i] = 0;
      }
    }

    void loop() {
      // read the value from the sensor:
      if (ind < countto) {
      starts[ind] = micros();
    //  delay(50);
      sensorValue[ind] = analogRead(sensorPin);
      ends[ind] = micros();
      vals[ind] = ends[ind] - starts[ind];
    //  Serial.println("Test");
        Serial.print(ind);
        Serial.print('\t');
        Serial.print(starts[ind]);
        Serial.print('\t');
        Serial.print(ends[ind]);
        Serial.print('\t');
        Serial.print(vals[ind]);
        Serial.print('\t');
        Serial.print('|');
        Serial.print('\t');
      Serial.print('\n');
      Serial.print('\r');
      ind++;
      }
      else if (stopprint == 0) {
        Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
        for (int j = 0; j < countto; j++) {
    //        Serial.println(j);
            Serial.print(starts[j]);
            Serial.print('\t');
            Serial.print(ends[j]);
            Serial.print('\t');
            Serial.print(vals[j]);
            Serial.print('\n');
            Serial.print('\r');
            stopprint = 1;
        }
      }
      else if (stopprint == 1) {
        while(1);
      }
    //  Serial.print(ind-1);
    //  Serial.print('\t');
    //  Serial.print(starts[ind-1]);
    //  Serial.print('\t');
    //  Serial.print(ends[ind-1]);
    //  Serial.print('\t');
    //  Serial.print(vals[ind-1]);
    //  Serial.print('\n');
    //  Serial.print('\r');
   }

Also, I'm using the Arduino Zero if it makes a difference.

Not sure if it is related to your problem but... if I were to try such a
measurement, I would use local variables, like
unsigned int start = micros();
int value = analogRead(sensorPin);
unsigned int end = micros();
sensorValue[ind] = value;
starts[ind] = start;
ends[ind] = end;
vals[ind] = end - start;

This way you would be measuring the time it takes to call both
analogRead() and micros(), and very little more. If you do something
like
sensorValue[ind] = analogRead(sensorPin);

then you are also measuring the time taken by the pointer arithmetic and
the memory access.
I generally program AVR-based Arduinos. These have a load-store
architecture, where saving to a local variable costs essentially
nothing, as the variable is typically assigned a CPU register by the
compiler. Saving to a global takes more time because of the RAM access.
I have no experience with ARM-based Arduinos, like the Zero, but I
believe it's also a load-store architecture, thus the same
considerations should probably apply.
Update: I tried the following experiment on my Uno:
#define PRINT_WHILE_READING

#define READ_COUNT 100

void setup() {
    unsigned int starts[READ_COUNT];
    unsigned int ends[READ_COUNT];
    unsigned int vals[READ_COUNT];

    Serial.begin(57600);
    Serial.println("Ready to begin");

    // Take the readings.
    for (int i = 0; i < READ_COUNT; i++) {
        starts[i] = micros();
        analogRead(A1);
        ends[i] = micros();
        vals[i] = ends[i] - starts[i];
#if defined(PRINT_WHILE_READING)
        Serial.print(i);
        Serial.print('\t');
        Serial.print(starts[i]);
        Serial.print('\t');
        Serial.print(ends[i]);
        Serial.print('\t');
        Serial.println(vals[i]);
#endif
    }

#if !defined(PRINT_WHILE_READING)
    // Print them now.
    Serial.println("All data taken");
    for (int i = 0; i < READ_COUNT; i++) {
        Serial.print(i);
        Serial.print('\t');
        Serial.print(starts[i]);
        Serial.print('\t');
        Serial.print(ends[i]);
        Serial.print('\t');
        Serial.println(vals[i]);
    }
#endif
}

void loop() {}

If PRINT_WHILE_READING is defined as above, I get times that fluctuate
between 108 and 116 µs. If I comment out the line
#define PRINT_WHILE_READING, I get mostly 116 µs and,
occasionally, 124 µs. In both cases, the first reading takes longer
(208 and 212 µs respectively).
The fact that the first reading takes longer is explained in the
datasheet: the ADC does some initializations in that first reading. All
measured times are multiples of 4 µs because that is the resolution
of micros().
Now, trying to understand the differences between the two cases:

With PRINT_WHILE_READING the times are shorter on average. This is
because the numbers are not stored in RAM, as the compiler figured
out the arrays starts[], ends[] and vals[] are not really
needed and optimized them away. When PRINT_WHILE_READING is not
defined, I can see the “store in RAM” instructions in the generated
assembly.
With PRINT_WHILE_READING the numbers fluctuate more. I guess this
is due to the printing through the serial port taking a variable
amount of time depending on the numbers being printed, and thus
creating timing inconsistencies.

The last point deserves some explanation. The ADC is clocked by a
prescaler that divides the frequency of the main clock by 128. This
gives a clock period of 8 µs. When an ADC conversion is started,
the ADC waits for the next rising edge of its clock, which can take
anywhere between 0 and 8 µs, then it does the conversion in
13 cycles of its clock. This means the whole process can take
anywhere between 104 and 112 µs depending on the exact time the
conversion is started relative to the phase of the prescaler. If the
conversions are started at irregular intervals, you expect to see
roughly 8 µs of fluctuation in the measured times.
All these observations have been done on an Uno, which is based on an
AVR clocked at 16 MHz. I know the Zero is quite different. You will
have to look at the datasheet of the ATSAMD21G18 to see whether anything
of the above can be extrapolated to the Zero.

I tried changing it to your format and nothing changed.  Thanks for the idea though.  If you have any more ideas about what could be causing it I'd really appreciate it!

If you understand ARM assembly, you could disassemble the program to see the code generated by the compiler. That's what I would do on an AVR to try to understand that kind of issue, but I cannot read ARM assembly.

That's more or less what I've been doing for about an hour now, but I haven't really found anything that would explain it

@Alexandra: I've updated the answer with some experiments done on my Uno. Maybe some of these results could be extrapolated to the Zero.

Thanks for the information.  I'm now just trying to get the time down from what the analogRead() timing is.  The datasheet says it should take ~100 microseconds per read (on the Arduino Zero at least which I'm using), but by driving pins high to measure it, it's still taking about 400 microseconds.  I've put the ADC in freerun mode and tried changing the prescaler but it doesn't even get close to 100 microseconds.  I saw posts of people trying to get it below 100 us previously, but I'm not even reaching that baseline and I'm not sure why.  Any ideas? (also posted on other comment, sorry)

@Alexandra: No idea, sorry. I think at this point only someone with good knowledge of that particular chip could help.

If you have access to a digital scope, try bracketing your code with changes to the state of an output pin. print() has a lot of moving parts, some (like buffer size, interrupt implementation) will vary with various Arduinos as others have noted. I am mostly using ARM Cortex M4 on Teensy 3.2. If I want to time something really precisely I will drive an I/O pin (with digitalWrite()) at the beginning and end of what I want to time. This has super fast execution. You could use more than one pin to see two things at once. Then, look at them on an oscilloscope. Trigger on the starting edge of the most important signal. Adjust the time scale to encompass the active pin level time. With a digital scope you can set persistence to infinite and then you can see the variation on the trailing edge of the pulse. You can move the digitalWrite points around in your program until you see what is causing the variation. millis() and micros() are 32-bit values so on an 8-bit AVR that is multiple machine cycles to access. A single digitWrite is usually one machine cycle so it is quick even on a slowly-clocked 8-bit AVR. Once you find the place where most of the variation occurs you at least have a quantified smoking gun to tell you what details to excavate further.

A call to digitalWrite() on an AVR takes anywhere from 78 to 108 cycles, depending on the pin number and the value written. That's why, for time-critical tasks, people resort to direct port access: something like PORTB |= _BV(5) compiles into a single machine instruction and executes in two cycles.

On the other hand, for precise timing, you can set the 16-bit timer to run at F_CPU and read it directly, which only takes 4 cycles. If you want to be accurate to the cycle, you will have to look at the generated assembly to see what exactly you have between the timer reads.

Thanks for the information.  I'm now just trying to get the time down from what the analogRead() timing is.  The datasheet says it should take ~100 microseconds per read (on the Arduino Zero at least which I'm using), but by driving pins high to measure it, it's still taking about 400 microseconds.  I've put the ADC in freerun mode and tried changing the prescaler but it doesn't even get close to 100 microseconds.  I saw posts of people trying to get it below 100 us previously, but I'm not even reaching that baseline and I'm not sure why.  Any ideas?


text:
Arduino changing output based on wire voltage
I’m new to arduino and I want to build myself smart switch that can be turned of both manualy and via wifi, is there any way to change position of relay based on if another wire is live or not? Im from europe so we have 230V  outlets.
Thanks for the answer.

" change position of relay based on if another wire is live or not?" - What does that mean?

If pysical switch is on then the wire passing thru is live, and id like to make decisions in arduino based on that, for example physical switch is on, then arduino switches relay conected to itself off and vice versa

It may make more sense with a concrete example of how this thing you're building is can be used.

Well, i want to use wifi controled smart switch and also be able to use my normal physical switch even if i turned my lights off with smart switch and also to be able to turn on lights with smart switch even when its truned off by physical switch. So my idea was to split live wire into 3 - one to arduino controled relay, one to normal swich and one to smart switch, and id like to be able to check if wire after normal switch and also after smart is still live so i can base some logics and determine if light should be on or off. I hope i made it clearer.

If I turn your description into a diagram, it might be clearer.  But then, it makes more sense for you to make the diagram and include that in your question along with the description.

I never did a diagram before, but i will try my best to make it right

Well i tried my best, it looks horible and not even speaking about the technical side, but I hope it is enough to understand my problem, I need to know name of the thing that returns true or false based on if is wire live, and it has to be able to handle 230V for long periods of time. My sketch -> https://i.imgur.com/erxAwkC.png

@krystof18, it seems to have done the job just fine.

Maybe a wire coil wound around the wire could pick up the frequency. Though I won't write about this, since I don't know much about how you would measure this, and because I think, that you are looking the wrong way.
You want to switch one device with multiple switches (how these switches are operates is not important for now). You can look at how this is normally done in eletrical installations. Here the switches are all connected to your breaker box. And there is one component, that waits for trigger signals from the switches and will switch the target device (the light in this case) accordingly. So in the end there is only one place, where the light is switched: in the breaker box. The switches in the room are only triggers. The current for the light does not flow through them. Also they don't necessarily need to carry mains voltage (triggers could also be low voltage) (though it seems they are in fact just using mains voltage, for which I don't know the reason. Maybe to avoid additional voltage conversion).
So I propose the following solution: The mains wires (230V) are only connected to the light and a (suitable) relay board. The relay board is connected to the Arduino, which can act as a Smart Switch (switching via WiFi, time based or whatever). For manual switching you can connect a switch or button to the Arduino and program the Arduino to read it and control the relay accordingly.
This solution is way easier, than trying to sense the live voltage on the lines, and this will most likely make it more reliable . It comes down to controlling an relay board and reading a button/switch, both things with tons of tutorials on the web
Note: Since mains voltage is always really dangerous, you should be really really caution. Don't use mains voltage, when developing your device. A simple LED with current limiting resistir connected to the power line of the Arduino through the relay is sufficient to check the complete functionality. Only connect mains voltage, if you are really really sure, that you did everything correct

source: Stack Exchange

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

sort: votes


text:
Getting all data of my JSON object from Serial.read() at once
I'm new to Arduino and I'm building a project that fetches data from a website (using ESP8266) and then transfers them to my Arduino UNO via serial port.
Data coming from ESP8266 every 20s - [{"x": 0,"y": 0,"rgb": [255, 200, 174]},{"x": 1,"y": 0,"rgb": [255, 200, 174]},{"x": 2,"y": 0,"rgb": [255, 200, 174]}]
But when I print the data like this

void loop() {

  if (Serial.available()) {
    Serial.write(Serial.read()); // This line prints only one character out of whole string

    data =  Serial.read(); // so this doesn't work

    DeserializationError error = deserializeJson(response, data);
    if (error) {
      Serial.print(F("deserializeJson() failed: "));
      Serial.println(error.f_str());
      return;
    }
    for (JsonObject elem : response.as<JsonArray>()) {
      int x = elem["x"]; // 2, 2, 2
      int y = elem["y"]; // 2, 2, 2
      JsonArray rgb = elem["rgb"];

      int rgb_0 = rgb[0]; // 255, 255, 255
      int rgb_1 = rgb[1]; // 255, 255, 255
      int rgb_2 = rgb[2]; // 255, 255, 255
      //Serial.print(x);
    }
  }
  delay(1000);   //then it waits 1 second and goes from the start
}

How can I make it to get the whole string and save it into a variable?
Thanks, much for answering.

There is no such thing as "a whole string" in serial. There is only single bytes. It is your job to decide (and program it so it understands) what a string is.

Then how can I watch for example for line break?

WHy do yoiu ithink you need to? And if you want to get serial data into a variable and then use that serial data for some other thing, just use whatever you stored in your variable. Once you read from serial it's gone from serial forever. But you saved it in data, so just use it from there?

What about Serial.readStringUntil() and read to e. g. \n?

I was going to put this as a comment, but maybe it belongs as an answer:
For what it's worth, ArduinoJSON seems to be able to deserialize directly from a stream, i.e. Serial, which may obviate the question as asked.  Presumably it knows where to stop deserializing, because it knows when it has received an entire JSON object; being a proper JSON parser, it can probably work this out better than you can without, you know, writing a JSON parser.
The following was just thrown together, now the author is here you should probably just follow their direction, but here's the code anyway:
#include <ArduinoJson.h>

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  Serial.setTimeout(30000);
}

void print_transmission_counter( {
    static unsigned long received_object_counter;
    Serial.println(F("\n\n\n\n"));
    for (int i = 0; i < 30; ++i) {
        Serial.write('-');
    }
    Serial.write('[');
    Serial.print(received_object_counter++);
    Serial.println(']');
}

void loop() {
    static StaticJsonDocument<256> json_doc;
    static bool led_state;

    print_transmission_counter();

    const auto deser_err = deserializeJson(json_doc, Serial);
    if (deser_err) {
        Serial.print(F("Failed to deserialize, reason: \""));
        Serial.print(deser_err.c_str());
        Serial.println('"');
    } else  {
        Serial.print(F("Recevied valid json document with "));
        Serial.print(json_doc.size());
        Serial.println(F(" elements."));
        Serial.println(F("Pretty printed back at you:"));
        serializeJsonPretty(json_doc, Serial);
        Serial.println();
    }

    // Just give some visual indication that the loop is progressing
    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
}

//  vim:sw=2:ts=2:et:nowrap:ft=cpp:

Thanks much, this sounds like the thing I need.

If this ends up being the route you take, and doing so doesn't invalidate any other answers (that may appear between now and then), you might consider changing the question title slightly to "Getting all data of my JSON object from Serial.read() at once" to improve findability and matching between question and answer.

It definitely looks like a great way to do it, but I can't seem to make it work, when I change the data variable to Serial.read() like this DeserializationError error = deserializeJson(response, Serial.read());  I get  Error compiling for board arduino UNO

It may be a while, but I'll reread your comment above and see if I can't provide a minimal example.  The ArduinoJSON documentation is quite good though, so I expect there will be one there as well.

@krystof18, please have a look at How to do serial communication between two boards?

@krystof18, with regard to the specific line given above, it's expecting a reference to a Stream, which Serial is.  By calling .read() there you're trying to pass a single character (or indication of the lack of a character; -1) into the deserializeJson function.

@BenoitBlanchon, do you mind if I draw your comment up into the answer body?

@timemage, I don't mind; please do.

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


text:
Arduino UNO with integrated ESP2866 wifi not working correctly
I bought this "knockoff" Arduino UNO with an integrated ESP 2866 wifi module. But I can't make it work. I've followed this tutorial because it's the same product as I have, but I can't make it work anyway - even blinking with LED doesn't work. Does anyone have experience with this exact (or similar) board with integrated ESP2866? I would be really glad for any help. link to the product. If you need to know anything else, I'll try my best to answer it.
My problem:
The board normally loads into IDE and i can send code to it. But after I do that, I get this:
Executable segment sizes:
IROM   : 228624          - code in flash         (default or ICACHE_FLASH_ATTR)
IRAM   : 26756   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)
DATA   : 1248  )         - initialized variables (global, static) in RAM/HEAP
RODATA : 688   ) / 81920 - constants             (global, static) in RAM/HEAP
BSS    : 24880 )         - zeroed variables      (global, static) in RAM/HEAP
Sketch uses 257316 bytes (24%) of program storage space. Maximum is 1044464 bytes.
Global variables use 26816 bytes (32%) of dynamic memory, leaving 55104 bytes for local variables. Maximum is 81920 bytes.
esptool.py v2.8
Serial port COM6
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: 2c:f4:32:44:1f:0b
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Erasing flash (this may take a while)...
Chip erase completed successfully in 8.7s
Compressed 261472 bytes to 193136...
Wrote 261472 bytes (193136 compressed) at 0x00000000 in 17.0 seconds (effective 122.9 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

But the LED doesn't blink.

The link to the tutorial is invalid. Please provide a valid link

@chrisl Sorry, changed it

I don't know why the answer below is accepted, as it clearly doesn't solve the question but also gives false information. In this answer @chrisl assumed that blinking green LED is what was programmed with sketch, but if you will open sketch used in this video and read comments in the source code, then this misconception will become obvious: actually red RX LED is what was programmed.
This board has two independent chips: ATmega328P and ESP8266, and ESP8266 built-in LED is combined with RX LED. So when you are blinking with ESP8266 LED, you are blinking with RX led.
And this is what tricked most people answering here, as they were looking on green blinking LED, which is controlled by ATmega328P.
Having said that, I also have to admit that I don't have solution for original question and I don't know why it doesn't work for @krystof18, but in video it clearly works.
EDIT:
TL/DR:
Don't use LED_BUILTIN, but attach an external LED and a resistor to ESP GPIO pins. Modify the sketch to use correct pin and upload while switches 5,6 and 7 are ON. Then disconnect the board and turn switch 7 OFF. Then you have to power board again and it should work.
Long explanation:
I have a board visually similar to what is on the video tutorial you have posted, but for me the blink example doesn't work, probably because LED is wired to some other PIN, rather than #defined for LED_BUILTIN. But I managed to get it working using this tutorial! Watch from 5:58. (Please note this video is in language I don't understand and have no idea what language it is, but the video itself is so obvious, that you basically don't need to understand what does that guy say).
Basically in this tutorial it is just blink example, but using external LED, instead of built-in. If you look at your board, then you can find 4x3 bar of pins located near 0, 1 and 2 Arduino digital pins. This bar is labelled "ESP pins" and it is what is says: ESP8266 pins. Pin labels are on the back of the board.
So this guy in video just connects GPIO16 and GND pins to a LED with resistor, and then modifies original blink example to use 16 instead of LED_BUILTIN. Then he uploads it to his board with switches 5,6 and 7 ON. Then he plugs-off the board and turns switch 7 OFF, so only switches 5 and 6 are on. Then he plugs board back in and it works!
I tried it and it works for me, hooray!
Also, if anyone can tell me what language this guy speaks in the video tutorial I posted - I am just curious! :)

You seem to have more knowledge than me within this topic, so do you know how do i make these two chips comunicate? And in best scenario, even transfer small amount of data?

I got this board recently and still trying to understand how to work with it properly. I was able to successfully upload sketch for ATmega328, with proper switch setup, as per table mentioned in response above, but when I change switches to USB->ESP8266 sketch update, then it seems to be uploaded fine, but then just doesn't work :( I will continue my efforts and will let you know if I'll be successful.

Hey, @krystof18, I managed to get it working and edited my original answer! Hope it will work for you too! Please let me know.

I know it's been a while, but I had a lot to do and today I finally got time for that and I wanted to thank you so much, it works for me now too. Did you find a way to transfer for example an array (or how is it called in Arduino IDE) to the atmega chip? Thanks much for the second time. BTW the language is Indoneese according to google translator.

You are obviously currently programming the ESP8266, not the Atmega328p. The board seems to have DIP switches on it. With those you can control, which chip is connected to which. The product description has the following table
Connection  DIP
1   2   3   4   5   6   7
ATmega328<->ESP8266     ON  ON  OFF     OFF     OFF     OFF     OFF
USB <->ATmega328    OFF     OFF     ON  ON  OFF     OFF     OFF
USB<->ESP8266 (Update firmware or sketch)   OFF     OFF     OFF     OFF     ON  ON  ON
USB<->ESP8266 (communication)   OFF     OFF     OFF     OFF     ON  ON  OFF
All independent     OFF     OFF     OFF     OFF

If you want to program the Atmega328p on it, you need set the DIP switches to the combination "USB <-> Atmega328". Currently you most likely have the combination "USB<->ESP8266 (Update firmware or sketch)", which means, that the ESP is connected to the USB chip (and thus to the PC) for programming. For blinking the Arduinos buildin LED you need to program the Atmega328p.

About the blink sketch: In the tutorial video he programs the ESP. But in the blink example he changes the delay time to 5000, which would mean on and off times of 5s. The LED, that he is pointing to, is blinking much faster, though he doesn't address this. I think he actually has the standard blink sketch on the Atmega and only pretends (or just didn't notice) that this happened due tp his programming. As you don't see a blink with the ESP, but with the Atmega, I would guess, that the LED marked with L is connected only to the Atmega (like on a normal Uno) and the ESP doesn't have any LED to blink connected. So everything is actually working as expected, the tutorial was just bad at that point.

In the tutorial, he uses contection USB <-> ESP8266 and example that is mentioned for ESP8266, i don’t think I made mistake there, but you can tell better if you watch the tutorial. My switch setup is 1,2,3,4-off 5,6,7-on 8-off

What is shown in that tutorial doesn't really add up. He changed the delay in the ESP8266 blink sketch to 5000. That would mean the LED stays on for 5s, then goes off for 5s and repeat. The LED in the video blinks way faster than that. I guess he has the standard blink on the Atmega328p and now tells us, that that is his changes code. Please try the standard blink sketch on the Atmega328p. Then we can test that hypopyhsis

Its advertised as UNO, but UNO in IDE doesn’t work, what device should i pick for that?

What do you mean with "doesn't work"? Aren't you able to upload to it? Have you changed the DIP switches to "USB <->Atmega328"? Maybe it comes without a bootloader. Then you would need to burn it to the Atmega via ISP (using another Arduino or an ISP programmer). Or maybe it has the old bootloader. Then you need to choose the corresponding option in the menu

My bad, sorry it does work, I just switched it wrongly, it's late :D And yes, normal blink works perfectly

Also what I noticed, even if I change the switches to set up in tutorial and run ESP8266 blink, it blinks in the interval I set on the normal blink, so nothing blinked on his side too I guess.

The ESP8266 blink only works, if there is actually an LED connected to that pin of the ESP on the board. Most likely the ESP just doesn't have an LED connected

@krystof18 I added a small paragraph about that in my answer, since comments are temporary. If you consider my answer as correct, you can mark it as correct.


text:
Accelerometer sample code
Just to illustrate my work here, I found a tutorial on how to code an accelerometer, I wanted to understand how does it work, literally get how it works, and not simply using the code without understanding it.
In the beginning of the program,there's a char variable declared as :
char values[10];
then later on the code, there was couple lines of getting the information stored in this variable, I'll give this as as example :
x = ((int)values[1]<<8)|(int)values[0];
we want X to receive values[0] and values[1] , that's what that line does up there.
My question is : can someone explain to me how does that line work, and why can't we simply write it as x = ((int)values[1])|(int)values[0]; ?

char values[10] is actually declaring an array of 10 chars - but none of them are assigned values (presumably the values get set when reading data from the sensor). Those array values are accessed using values[0] ..to.. values[9].  So when it uses (int)values[1] it is referring to the second char in the array (and casting it to an int).

To understand this you have to start thinking in binary.
The | operator is "Perform a binary OR on these two values".
The <<8 is "Shift this value 8 bits to the left".
If you have two 8-bit values, say (in hex) 0x37 and 0x42, and you OR them together you get:
0x37 = 00110111
0x42 = 01000010
--------------- |
0x77 = 01110111

In each column where there is a 1 in either value you get a 1 in the result.
Now if you shift the first number 8 bits to the left, you end up with:
0x3700 = 0011011100000000
0x0042 =         01000010
------------------------- |
0x3742 = 0011011101000010

You do this when a 16-bit value has been split into two 8-bit values and you want to join them back together again into the original 16-bit value.

up in the beginning of the program, there's a char variable declared
  as: char values[10];

This is not a “char variable”, it's an “array of 10 chars”.

((int)values[1]<<8)|(int)values[0]

Majenko's answer perfectly explains the intent of the author of the
tutorial, but that is not necessarily what the code actually does. As
it stands, this piece of code is buggy. Or, to say the least, it has a
serious portability problem: it will probably work fine on ARM-based
boards, but it will fail on AVR-based boards, and on x86.
The reason is that, in C and C++, the type char can be either signed
or unsigned, depending on the platform. On most platforms, including
AVR, it is signed. This implies that, when a char is converted to
int, it undergoes sign extension instead of being just zero
padded. To put it graphically, let's assume the sign bit (most
significant bit) of values[0] is s, then:
values[0]      =         sxxxxxxx
(int)values[0] = sssssssssxxxxxxx

Here I am assuming an AVR (16-bit ints). If the sign bit happens to be
zero, this will work as intended. This is the case in Majenko's example.
But if we replace 0x42 with 0xa2, we will have:
values[1]         =   0x37 =         00110111
(int)values[1]    = 0x0037 = 0000000000110111
(int)values[1]<<8 = 0x3700 = 0011011100000000
values[0]         =   0xa2 =         10100010
(int)values[0]    = 0xffa2 = 1111111110100010

Then, the bitwise OR gives
0x3700 = 0011011100000000
0xffa2 = 1111111110100010
------------------------- |
0xffa2 = 1111111110100010

and the data in values[1] is lost.
Conclusion: values should be declared as an array of unsigned
chars, as this will enforce zero-padding instead of sign extension.
Always use unsigned types when doing bit manipulations. And you probably
should find a better tutorial to learn this kind of stuff.

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


text:
Connecting Arduino to PC through Slimline SATA instead of USB?
I removed the DVD-RW from my laptop and want to use the new area as an IO port instead. There is an Arduino Nano with me which can fit into the emptied out drive space and there are some easy to connect IO headers with me.
The only (major) problem is how can i connect the Arduino to the slimline SATA port of the DVD drive. There are some SATA to USB converters available in the market, but will they work? (as i am trying to connect it the other way around)
Is there any possible way to connect the Arduino to the SATA port, and even if i would be able to connect it, would i be able to use it as a regular Arduino as if it were connected to a USB port?

No, there is no way of connecting an Arduino to a SATA port. You require USB or UART. SATA is a specific dedicated port, whereas USB is, as the name suggests, Universal. So USB can become SATA but SATA can never become USB.

Ok, that must be the case. Why else are there no available products? Is it so because the protocol used in SATA does not support what USB supports?

SATA supports SATA and only SATA. Because SATA is SATA. It is, as its name suggests, Serial ATA. Nothing more, nothing less. USB is a UNIVERSAL Serial Bus. It's like a piece of wire. SATA is the metal down the middle, and USB is the plastic round the outside. The plastic can contain the metal, but the metal cannot contain the plastic. The plastic could also contain a fibre optic instead of the metal. Or it could contain water. Or air. Or any other number of things. The metal will always be the metal though.

There is a USB port right next to the CD drive. I think i could solder those USB pins with 2 switches to connect / disconnect data with the arduino. That way if no device is connected to that usb port, i could connect it to the arduino.

Doable, sure. You may also find another USB port inside the computer somewhere. Maybe there is an SD card slot that is connected through USB you could sacrifice, for example.

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


text:
How can I handle the millis() rollover?
I need to read a sensor every five minutes, but since my sketch also has
other tasks to do, I cannot just delay() between the readings. There
is the Blink without
delay tutorial
suggesting I code along these lines:
void loop()
{
    unsigned long currentMillis = millis();

    // Read the sensor when needed.
    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        readSensor();
    }

    // Do other stuff...
}

The problem is that millis() is going to roll over back to zero after
roughly 49.7 days. Since my sketch is intended to run for longer
than that, I need to make sure the rollover does not make my sketch
fail. I can easily detect the rollover condition
(currentMillis < previousMillis), but I am not sure what to do then.
Thus my question: what would be the proper/simplest way to handle the
millis() rollover?

Editorial note: This is not exactly a question of mine, rather a tutorial in a question/answer format. I have witnessed a lot of confusion on the Internet (including here) about this topic, and this site seems like the obvious place to search for an answer. This is why I am providing this tutorial here.

I would do previousMillis += interval instead of previousMillis = currentMillis if I wanted a certain frequency of results.

@Jasen: That's right! previousMillis += interval if you want constant frequency and are sure that your processing takes less than interval, but previousMillis = currentMillis for guaranteeing a minimum delay of interval.

One of the "tricks" I use is to lighten the load on the arduino by using the smallest int that contains the interval. For instance, for max 1 minute intervals, I write uint16_t previousMillis; const uint16_t interval = 45000; ... uint16_t currentMillis = (uint16_t) millis(); if ((currentMillis - previousMillis) >= interval) ...

@frarugi87: I sometimes do the same. Note however that, if that type turns out to be smaller than int (uint8_t, but also uint16_t on ARM), you have to cast the result of the subtraction to the appropriate type. Otherwise, because of integer promotions, you end up with the wrong type. BTW, the cast you did write (casting millis()) is redundant.

@EdgarBonet I never totally understood the automatic promotions, so forgive me if this question seems stupid, but.. if all the elements (currentMillis, previousMillis, interval) are uint16_t, will it "promote" the subtraction to let's say int32_t (and so break what I wanted to do)? As for the cast, it's just out of habit (implicit casts raise MISRA warnings, so I tend to avoid implicit casts)

@frarugi87: For each binary operation, if both arguments are smaller than a plain int, then they are both implicitly promoted to int. Otherwise the smaller is converted to the type of the larger, with a preference to the unsigned types (I am oversimplifying a bit, but it's the main idea).

@EdgarBonet thanks for the explanation; I need to keep this in mind when doing <250ms cycles on 8-bit processors to save memory... (8-bit operations on 16-bit processors, as well as 8/16-bit operations on 32-bit processors, do not save memory nor flash)

I wish some answer included opinion on restarting your device, or solution where you manually detect overflow (millis() < 1000) and reset variables timestamps that use nextUpdateMillis as if (currentMillis <= nextUpdateMillis) { }.

Short answer: do not try to “handle” the millis rollover, write
rollover-safe code instead. Your example code from the tutorial is fine.
If you try to detect the rollover in order to implement corrective
measures, chances are you are doing something wrong. Most Arduino
programs only have to manage events that span relatively short
durations, like debouncing a button for 50 ms, or turning a heater
on for 12 hours... Then, and even if the program is meant to run
for years at a time, the millis rollover should not be a concern.
The correct way to manage (or rather, avoid having to manage) the
rollover problem is to think of the unsigned long number returned by
millis() in terms of modular
arithmetics. For the
mathematically inclined, some familiarity with this concept is very
useful when programming. You can see the math in action in Nick Gammon's
article millis() overflow ... a bad
thing?. For the problem at hand,
what's important to know is that in modular arithmetics the numbers
“wrap around” when reaching a certain value – the modulus – so that
1 − modulus is not a negative number but 1 (think of a
12 hour clock where the modulus is 12: here 1 − 12 = 1).
For those who do not want to
go through the computational details, I offer here an alternative
(hopefully simpler) way of thinking about it. It is based on the simple
distinction between instants and durations. As long as your tests
only involve comparing durations, you should be fine.
Note on micros(): Everything said here about millis() applies
equally to micros(), except for the fact that micros() rolls over
every 71.6 minutes, and the setMillis() function provided below
does not affect micros().
Instants, timestamps and durations
When dealing with time, we have to make the distinction between at least
two different concepts: instants and durations. An instant is a
point on the time axis. A duration is the length of a time interval,
i.e. the distance in time between the instants that define the start and
the end of the interval. The distinction between these concepts is not
always very sharp in everyday language. For example, if I say “I will
be back in five minutes”, then “five minutes” is the estimated
duration of my absence, whereas “in five minutes” is the instant
of my predicted coming back. Keeping the distinction in mind is
important, because it is the simplest way to entirely avoid the rollover
problem.
The return value of millis() could be interpreted as a duration: the
time elapsed from the start of the program until now. This
interpretation, however, breaks down as soon as millis overflows. It is
generally far more useful to think of millis() as returning a
timestamp, i.e. a “label” identifying a particular instant. It could
be argued that this interpretation suffers from these labels being
ambiguous, as they are reused every 49.7 days. This is, however,
seldom a problem: in most embedded applications, anything that happened
49.7 days ago is ancient history we do not care about. Thus,
recycling the old labels should not be an issue.
Do not compare timestamps
Trying to find out which among two timestamps is greater than the other
does not make sense. Example:
unsigned long t1 = millis();
delay(3000);
unsigned long t2 = millis();
if (t2 > t1) { ... }

Naively, one would expect the condition of the if () to be always
true. But it will actually be false if millis overflows during
delay(3000). Thinking of t1 and t2 as recyclable labels is the
simplest way to avoid the error: the label t1 has clearly been assigned
to an instant prior to t2, but in 49.7 days it will be reassigned
to a future instant. Thus, t1 happens both before and after t2. This
should make clear that the expression t2 > t1 makes no sense.
But, if these are mere labels, the obvious question is: how can we do
any useful time calculations with them? The answer is: by restricting
ourselves to the only two calculations that make sense for timestamps:

later_timestamp - earlier_timestamp yields a duration, namely the
amount of time elapsed between the earlier instant and the later
instant. This is the most useful arithmetic operation involving
timestamps.
timestamp ± duration yields a timestamp which is some time after
(if using +) or before (if −) the initial timestamp. Not as useful as
it sounds, since the resulting timestamp can be used in only two
kinds of calculations...

Thanks to modular arithmetics, both of these are guaranteed to work fine
across the millis rollover, at least as long as the delays involved are
shorter than 49.7 days.
Comparing durations is fine
A duration is just the amount of milliseconds elapsed during some time
interval. As long as we do not need to handle durations longer than
49.7 days, any operation that physically makes sense should also
make sense computationally. We can, for example, multiply a duration by
a frequency to get a number of periods. Or we can compare two durations
to know which one is longer. For example, here are two alternative
implementations of delay(). First, the buggy one:
void myDelay(unsigned long ms) {          // ms: duration
    unsigned long start = millis();       // start: timestamp
    unsigned long finished = start + ms;  // finished: timestamp
    for (;;) {
        unsigned long now = millis();     // now: timestamp
        if (now >= finished)              // comparing timestamps: BUG!
            return;
    }
}

And here is the correct one:
void myDelay(unsigned long ms) {              // ms: duration
    unsigned long start = millis();           // start: timestamp
    for (;;) {
        unsigned long now = millis();         // now: timestamp
        unsigned long elapsed = now - start;  // elapsed: duration
        if (elapsed >= ms)                    // comparing durations: OK
            return;
    }
}

Most C programmers would write the above loops in a terser form, like
while (millis() < start + ms) ;  // BUGGY version

and
while (millis() - start < ms) ;  // CORRECT version

Although they look deceptively similar, the timestamp/duration
distinction should make clear which one is buggy and which one is
correct.
What if I really need to compare timestamps?
Better try to avoid the situation. If it is unavoidable, there is still
hope if it is known that the respective instants are close enough:
closer than 24.85 days. Yes, our maximum manageable delay of
49.7 days just got cut in half.
The obvious solution is to convert our timestamp comparison problem into
a duration comparison problem. Say we need to know whether instant t1 is
before or after t2. We choose some reference instant in their common
past, and compare the durations from this reference until both t1 and
t2. The reference instant is obtained by subtracting a long enough
duration from either t1 or t2:
unsigned long reference_instant = t2 - LONG_ENOUGH_DURATION;
unsigned long from_reference_until_t1 = t1 - reference_instant;
unsigned long from_reference_until_t2 = t2 - reference_instant;
if (from_reference_until_t1 < from_reference_until_t2)
    // t1 is before t2

This can be simplified as:
if (t1 - t2 + LONG_ENOUGH_DURATION < LONG_ENOUGH_DURATION)
    // t1 is before t2

It is tempting to simplify further into if (t1 - t2 < 0). Obviously,
this does not work, because t1 - t2, being computed as an unsigned
number, cannot be negative. This, however, although not portable, does
work:
if ((signed long)(t1 - t2) < 0)  // works with gcc
    // t1 is before t2

The keyword signed above is redundant (a plain long is always
signed), but it helps make the intent clear. Converting to a signed long
is equivalent to setting LONG_ENOUGH_DURATION equal to
24.85 days. The trick is not portable because, according to the C
standard, the result is implementation defined. But since the gcc
compiler promises to do the right
thing,
it works reliably on Arduino. If we wish to avoid implementation defined
behavior, the above signed comparison is mathematically equivalent to
this:
#include <limits.h>

if (t1 - t2 > LONG_MAX)  // too big to be believed
    // t1 is before t2

with the only problem that the comparison looks backwards. It is also
equivalent, as long as longs are 32-bits, to this single-bit test:
if ((t1 - t2) & 0x80000000)  // test the "sign" bit
    // t1 is before t2

The last three tests are actually compiled by gcc into the exact same
machine code.
How do I test my sketch against the millis rollover
If you follow the precepts above, you should be all good. If you
nevertheless want to test, add this function to your sketch:
#include <util/atomic.h>

void setMillis(unsigned long ms)
{
    extern unsigned long timer0_millis;
    ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
        timer0_millis = ms;
    }
}

and you can now time-travel your program by calling
setMillis(destination). If you want it to go through the millis
overflow over and over again, like Phil Connors reliving Groundhog Day,
you can put this inside loop():
// 6-second time loop starting at rollover - 3 seconds
if (millis() - (-3000) >= 6000)
    setMillis(-3000);

The negative timestamp above (-3000) is implicitly converted by the
compiler to an unsigned long corresponding to 3000 milliseconds before
the rollover (it is converted to 4294964296).
What if I really need to track very long durations?
If you need to turn a relay on and turn it off three months later, then
you really need to track the millis overflows. There are many ways to do
so. The most straightforward solution may be to simply extend millis()
to 64 bits:
uint64_t millis64() {
    static uint32_t low32, high32;
    uint32_t new_low32 = millis();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

This is essentially counting the rollover events, and using this count
as the 32 most significant bits of a 64 bit millisecond count.
For this counting to work properly, the function needs to be called at
least once every 49.7 days. However, if it is only called once per 49.7 days, for some cases it is possible that the check (new_low32 < low32) fails and the code misses a count of high32. Using millis() to decide when to make the only call to this code in a single "wrap" of millis (a specific 49.7 day window) could be very hazardous, depending on how the time frames line up. For safety, if using millis() to determine when to make the only calls to millis64(), there should be at least two calls in every 49.7 day window.
Keep in mind, though, that 64 bit arithmetic is expensive on the
Arduino. It may be worth to reduce the time resolution in order to stay
at 32 bits.

So, you are saying that the code written in the question will actually work correctly?

@Jasen: Exactly! I've seem more than once people trying to “fix” the problem that did not exist in the first place.

I'm glad I found this. I've had this question before.

One of the best and most useful answers on StackExchange! Thanks a lot! :)

This is such an amazing answer to the question. I come back to this answer basically once a year because I am paranoid of messing rollovers.

This is a fantastic answer, except that it doesn't appear possible to "see" timer0_millis from a sketch anymore; you can declare it extern but the linker does not see it. wiring.c does not declare timer0_millis as static so I'm not sure what exactly they're doing, but the answer may need an update.

@AndrewKohlsmith: I just tested setMillis() on an Uno, with the Arduino IDE 1.8.10. It works as expected.

+1. Such an in depth answer that I think my millis() rolled over reading it.

For the use-case of scheduling future events, I really like the compare timestamp forms, rather than forcing them into the common pattern of comparing always non-negative durations since past events.  // You tested the three timestamp-comparison codes on GCC, do you know of compilers that do the the wrong thing/behave differently with the different codes?  // Would if ((t1 - t2) & 0x80000000)  // test the "sign" bit actually be portable on machines with wider unsigned long sizes?

@DaveX: Re: “do you know of compilers that do the the wrong thing [when converting an unsigned integer to signed]?”: I don't, and I don't think such a compiler would be easy to come by. Reducing an n-bit integer modulo 2^n is the only option that makes sense with two's complement, and other signed integer representations are practically gone. Note that, since C++20, this behavior is mandatory. Even though Arduino may not be using C++20, I take this as a sign that most current C++ implementations already do this.

@DaveX: Re: “Would if ((t1 - t2) & 0x80000000) [...] be portable on machines with wider unsigned long sizes”: That wouldn't test the sign bit (which is 0x8000000000000000 on a 64-bit long), but it would still work if t1 and t2 are less than 2^31 ms apart.

Thanks for this answer! If I am only interested in very short durations (say only debouncing switches), it seems like there's no reason to use the "unsigned long" type. I could go with a byte, as long as I don't intend to have durations longer than 255 ms,  right? (I understand that millis() returns an "unsigned long" but I could write my own function that returns a byte in this case)

@RobD: In principle, yes. You have, however, to be aware of the implicit conversions performed by C++. If started and now are bytes (type uint8_t), then now-started is a (potentially negative) int. Using unsigned int would be safer (no integral promotion) as long as you do not write an expression like millis()-started, which would implicitly convert started to unsigned long.

TL;DR Short version:
An unsigned long is 0 to 4,294,967,295 (2^32 - 1).
So lets say previousMillis is 4,294,967,290 (5 ms before rollover), and currentMillis is 10 (10ms after rollover). Then currentMillis - previousMillis is actual 16 (not -4,294,967,280) since the result will be calculated as an unsigned long (which can't be negative, so itself will roll around). You can check this simply by:
Serial.println( ( unsigned long ) ( 10 - 4294967290 ) ); // 16
So the above code will work perfectly fine. The trick is to always calculate the time difference, and not compare the two time values.

How about a 15ms before rollover and a 10ms after rollover (ie 49.7 days after). 15 > 10, but the 15ms stamp is nearly a month and a half old. 15-10 > 0 and 10-15 > 0 unsigned logic, so that is no use here!

@prakharsingh95 10ms-15ms will become ~49.7 days - 5ms, which is the correct difference. The math works until millis() rolls over twice, but that is very unlikely to occur to the code in question.

Let me rephrase. Suppose you have two timestamps 200ms and 10ms. How do you tell which is(are) rolled over?

@prakharsingh95 The one stored in previousMillis has to have been measured before currentMillis, so if currentMillis is smaller than previousMillis a rollover occurred. The math happens to work out that unless two rollovers have occurred, you don't even need to think about it.

Ah, ok. if you do t2-t1, and if you can guarantee t1 is measured before t2 then it's equivalent to signed (t2-t1)% 4,294,967,295, hence the auto wraparound. Nice!. But what if there are two rollovers, or interval is >  4,294,967,295?

Intervals larger that 49 days will be a bit more difficult, but in most applications not very useful, as the arduino crystal is not that accurate. Over 49 this inaccuracy could result in hours of error. Multiple rollovers can't occur since previousMillis is change when the interval has passed. PS the formula would actually be (t2-t1+4,294,967,295) % 4,294,967,295 since modulo will also give negative values (e.g. -3%2==-1)

does one need to cast the calculation result to unsigned long? Or will this be automatic if the calculation is executed with two variables already declared as unsigned long?

The accepted answer is very good but didn't explain this part.

I loved this question, and the great answers it generated. First a quick comment on a previous answer (I know, I know, but I don't have the rep to comment yet. :-).
Edgar Bonet's answer was amazing. I've been coding for 35 years, and I learned something new today. Thank you. That said, I believe the code for "What if I really need to track very long durations?" breaks unless you call millis64() at least once per rollover period. Really nitpicky, and unlikely to be an issue in a real-world implementation, but there you go.
Now, if you really did want timestamps covering any sane time range (64-bits of milliseconds is about half a billion years by my reckoning), it looks simple to extend the existing millis() implementation to 64 bits.
These changes to attinycore/wiring.c (I'm working with the ATTiny85) seem to work (I'm assuming the code for other AVRs is very similar). See the lines with the //BFB comments, and the new millis64() function. Clearly it's going to be both bigger (98 bytes of code, 4 bytes of data) and slower, and as Edgar pointed out, you almost certainly can accomplish your goals with just a better understanding of unsigned integer math, but it was an interesting exercise.
volatile unsigned long long timer0_millis = 0;      // BFB: need 64-bit resolution

#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
    // copy these to local variables so they can be stored in registers
    // (volatile variables must be read from memory on every access)
    unsigned long long m = timer0_millis;       // BFB: need 64-bit resolution
    unsigned char f = timer0_fract;

    m += MILLIS_INC;
    f += FRACT_INC;
    if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
        m += 1;
    }

    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;
}

// BFB: 64-bit version
unsigned long long millis64()
{
    unsigned long long m;
    uint8_t oldSREG = SREG;

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
    m = timer0_millis;
    SREG = oldSREG;

    return m;
}

You are right, my millis64() only works if it is called more frequently than the rollover period. I edited my answer to point out this limitation. Your version does not have this issue, but it carries another drawback: it does 64-bit arithmetics in interrupt context, which occasionally increases the latency in responding to other interrupts.

Wrap the millis() in a class!
Logic:

Use id's instead of millis() directly.
Compare reversals using id's. This is clean and rollover independent.
For specific applications, to calculate exact difference between two id's, keep track of reversals and stamps. Calculate the difference.

Keeping track of reversals:

Update a local stamp periodically faster than millis(). This will help you find out if millis() has overflown.
The period of the timer determines accuracy

class Timer {

public:
    static long last_stamp;
    static long *stamps;
    static int *reversals;
    static int count;
    static int reversal_count;

    static void setup_timer() {
        // Setup Timer2 overflow to fire every 8ms (125Hz)
        //   period [sec] = (1 / f_clock [sec]) * prescale * (255-count)
        //                  (1/16000000)  * 1024 * (255-130) = .008 sec

        TCCR2B = 0x00;        // Disable Timer2 while we set it up

        TCNT2  = 130;         // Reset Timer Count  (255-130) = execute ev 125-th T/C clock
        TIFR2  = 0x00;        // Timer2 INT Flag Reg: Clear Timer Overflow Flag
        TIMSK2 = 0x01;        // Timer2 INT Reg: Timer2 Overflow Interrupt Enable
        TCCR2A = 0x00;        // Timer2 Control Reg A: Wave Gen Mode normal
        TCCR2B = 0x07;        // Timer2 Control Reg B: Timer Prescaler set to 1024

        count = 0;
        stamps = new long[50];
        reversals = new int [10];
        reversal_count =0;
    }

    static long get_stamp () {
        stamps[count++] = millis();
        return count-1;
    }

    static bool compare_stamps_by_id(int s1, int s2) {
        return s1 > s2;
    }

    static long long get_stamp_difference(int s1, int s2) {
        int no_of_reversals = 0;
        for(int j=0; j < reversal_count; j++)
        if(reversals[j] < s2 && reversals[j] > s1)
            no_of_reversals++;
        return stamps[s2]-stamps[s1] + 49.7 * 86400 * 1000;
    }

};

long Timer::last_stamp;
long *Timer::stamps;
int *Timer::reversals;
int Timer::count;
int Timer::reversal_count;

ISR(TIMER2_OVF_vect) {

    long stamp = millis();
    if(stamp < Timer::last_stamp) // reversal
        Timer::reversals[Timer::reversal_count++] = Timer::count;
    else
        ; // no reversal
    Timer::last_stamp = stamp;
    TCNT2 = 130;     // reset timer ct to 130 out of 255
    TIFR2 = 0x00;    // timer2 int flag reg: clear timer overflow flag
};

// Usage

void setup () {
    Timer::setup_timer();

    long s1 = Timer::get_stamp();
    delay(3000);
    long s2 = Timer::get_stamp();

    Timer::compare_stamps_by_id(s1, s2); // true

    Timer::get_stamp_difference(s1, s2); // return true difference, taking into account reversals
}

Timer credits.

I edited the code to remove the maaaaany errors that prevented it to compile. This stuff will cost you about 232 bytes of RAM and two PWM channels. It will also start to corrupt the memory after you get_stamp() 51 times. Comparing delays instead of timestamps will certainly be more efficient.

Isn't that full static class effectively like namespace?


text:
Arduino Mega with Sensors and tftlcd 2.4 inch
I am working with tftlcd 2.4 inch with Arduino mega 2560 board. In this code I just want to show clock as my default or home screen. By clicking on clock at any point on screen user should get a new screen in which options of three sensors(pulse oximeter, glucose sensor and pedometer) are available. By selecting any sensor by touch, the value of that sensor will appear on screen. I also want to use Bluetooth module to send data to my mobile application. I did separate integration of all these sensors with Bluetooth module HC -06, but now I want to compile my all work. I have write a code for all this procedure which is given below:
    #include <Adafruit_GFX.h>

#include <Adafruit_TFTLCD.h>
#include <TouchScreen.h>
//#include <URTouch.h>
#include <Wire.h>
#include "MAX30105.h"
#include "spo2_algorithm.h"

MAX30105 particleSensor;

#define YP A2
#define XM A3
#define YM 8
#define XP 9
#define TS_MINX 275
#define TS_MINY 648
#define TS_MAXX 1023
#define TS_MAXY 623
#define MINPRESSURE 10
#define MAXPRESSURE 1000
#define LCD_CS A3
#define LCD_CD A2
#define LCD_WR A1
#define LCD_RD A0
#define LCD_RESET A4
#define MAX_BRIGHTNESS 255

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);
Adafruit_TFTLCD tft(LCD_CS,LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
uint16_t irBuffer[100];
uint16_t redBuffer[100];
#else
uint32_t irBuffer[100];
uint32_t redBuffer[100];
#endif

boolean buttonEnabled =true;
char currentpage, currentpcolour;
bool running;
//clock
uint16_t osx = 120, osy = 120, omx = 120, omy = 120, ohx = 120, ohy = 120, xpos;
uint32_t targetTime = 0;
uint8_t conv2d(const char* p) {
  uint8_t v = 0;
  if ('0' <= *p && *p <= '9')
    v = *p - '0';
  return 10 * v + *++p - '0';
}
uint8_t hh = conv2d(__TIME__), mm = conv2d(__TIME__ + 3), ss = conv2d(__TIME__ + 6);
boolean initial = 1;
char d;

//PulseOxi
int32_t bufferLength, spo2, heartRate; //data length, SPO2 value, heart rate value
int8_t validSPO2, validHeartRate; //indicator to show if the SPO2 calculation is valid, indicator to show if the heart rate calculation is valid
byte pulseLED = 11; //Must be on PWM pin
byte readLED = 13; //Blinks with each data read
byte ledBrightness = 60; //Options: 0=Off to 255=50mA
byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32
byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
int pulseWidth = 411; //Options: 69, 118, 215, 411
int adcRange = 4096; //Options: 2048, 4096, 8192, 16384

//Pedometer
const int xpin = A1;
const int ypin = A2;
const int zpin = A3;
byte p[8] = {
  0x1F,
  0x1F,
  0x1F,
  0x1F,
  0x1F,
  0x1F,
  0x1F,
  0x1F
};
float threshold = 100;
float xval[100] = {0};
float yval[100] = {0};
float zval[100] = {0};
float xavg, yavg, zavg;
int steps, flag = 0;

void drawClock(){
  tft.setTextColor(0xFFFF);
  tft.fillScreen(0x0000);
  xpos = tft.width() / 2;
  tft.drawCircle(xpos, 120, 125, 0xFFE0);
  tft.fillCircle(xpos, 120, 118, 0x001F);
  tft.fillCircle(xpos, 120, 110, 0x0000);
  for (int a=95; a<104; a++){
    tft.drawCircle(xpos, 120, a, 0xFFFF);
  }
  for (int i = 0; i < 360; i += 30) {
    tft.drawLine(((cos((i - 90) * 0.0174532925)) * 114 + xpos), ((sin((i - 90) * 0.0174532925)) * 114 + 120), ((cos((i - 90) * 0.0174532925)) * 100 + xpos), ((sin((i - 90) * 0.0174532925)) * 100 + 120), 0xFFE0);
  }
  for (int i = 0; i < 360; i += 6) {
    tft.drawPixel(((cos((i - 90) * 0.0174532925)) * 102 + xpos), ((sin((i - 90) * 0.0174532925)) * 102 + 120), 0x07E0);
    tft.drawLine(((cos((i - 90) * 0.0174532925)) * 102 + xpos), ((sin((i - 90) * 0.0174532925)) * 102 + 120), ((cos((i - 90) * 0.0174532925)) * 92 + xpos), ((sin((i - 90) * 0.0174532925)) * 92 + 120), 0x0000);
    tft.drawLine(((cos((i - 90) * 0.0174532925)) * 102 + xpos)+1, ((sin((i - 90) * 0.0174532925)) * 102 + 120)+1, ((cos((i - 90) * 0.0174532925)) * 92 + xpos)+1, ((sin((i - 90) * 0.0174532925)) * 92 + 120)+1, 0x0000);

    if (i == 0 || i == 180) tft.fillCircle(((cos((i - 90) * 0.0174532925)) * 102 + xpos), ((sin((i - 90) * 0.0174532925))* 102 + 120), 2, 0xFFFF);
    if (i == 90 || i == 270) tft.fillCircle(((cos((i - 90) * 0.0174532925)) * 102 + xpos), ((sin((i - 90) * 0.0174532925))* 102 + 120), 2, 0xFFFF);
  }
  tft.fillCircle(xpos, 121, 3, 0xFFFF);
  targetTime = millis() + 1000;
}

void setup() {
  tft.reset();
  tft.begin(0x9341);
  tft.setRotation(1);
  digitalWrite(13, HIGH);
  //TSPoint p = ts.getPoint();     // Read touchscreen
  digitalWrite(13, LOW);
  pinMode(XM, OUTPUT);
  pinMode(YP, OUTPUT);
  pinMode(pulseLED, OUTPUT);
  pinMode(readLED, OUTPUT);
  //first screen
  drawClock();
  currentpage = '0';
}

void loop() {
if (currentpage == '0') {
  TSPoint p = ts.getPoint();
  if (p.z > ts.pressureThreshhold) {
      p.x = map(p.x,TS_MAXX, TS_MINX , 0, 320);
      p.y = map(p.y,TS_MAXY, TS_MINY , 0, 480);
      if (p.x > 50 && p.x > 260 && p.y > 180 && p.y < 270 && buttonEnabled){
        buttonEnabled = false;
        tft.fillScreen(0x0000);
        currentpage = '1';
        drawHomeScreen();
      }
  }
}
   if (currentpage == '1') {
    TSPoint p = ts.getPoint();
     if (p.z > 10 && p.z < 1000) {
        if (p.x > 736 && p.x < 855 && p.y > 255 && p.y < 725  && p.z > MINPRESSURE && p.z < MAXPRESSURE)
        {
        Serial.println("Pedometer");
        currentpage = 2;
        calibrate();
      }
      else if (p.x > 563 && p.x < 683 && p.y > 275 && p.y < 750)
      {
        currentpage = 3;
        //drawGlu();
      }
      if (p.x > 403 && p.x < 525 && p.y > 271 && p.y < 725)
      {
        if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed
             {
              Serial.println(F("MAX30105 was not found. Please check wiring/power."));
              while (1);
             }
             Serial.println(F("Attach sensor to finger with rubber band. Press any key to start conversion"));
             while (Serial.available() == 0) ; //wait until user presses a key
             Serial.read();
             particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings
             currentpage = '4';
             drawPulseOxi();
      }
    }
  }
if (currentpage == '0') {
    if (targetTime < millis()) {
      targetTime = millis() + 1000;
      ss++;
      if (ss == 60) {
        ss = 0;
        mm++;
        if (mm > 59) {
          mm = 0;
          hh++;
          if (hh > 23) {
            hh = 0;
        }
      }
    }
 if (ss == 0 || initial) {
      initial = 0;
      // Erase hour and minute hand positions every minute
      tft.drawLine(ohx, ohy, xpos, 121, 0x0000);
      ohx = (cos(((hh * 30 + (mm * 6 + (ss * 6) * 0.01666667) * 0.0833333) - 90) * 0.0174532925)) * 62 + xpos + 1;
      ohy = (sin(((hh * 30 + (mm * 6 + (ss * 6) * 0.01666667) * 0.0833333) - 90) * 0.0174532925)) * 62 + 121;
      tft.drawLine(omx, omy, xpos, 121,  0x0000);
      omx = (cos(((mm * 6 + (ss * 6) * 0.01666667)- 90) * 0.0174532925)) * 84 + xpos;
      omy = (sin(((mm * 6 + (ss * 6) * 0.01666667) - 90) * 0.0174532925)) * 84 + 121;
    }
      // Redraw new hand positions, hour and minute hands not erased here to avoid flicker
      tft.drawLine(osx, osy, xpos, 121,  0x0000);
      osx = (cos(((ss * 6) - 90) * 0.0174532925)) * 90 + xpos + 1;
      osy = (sin(((ss * 6) - 90) * 0.0174532925)) * 90 + 121;
      tft.drawLine(osx, osy, xpos, 121, 0xF800);
      tft.drawLine(ohx, ohy, xpos, 121, 0x07FF);
      tft.drawLine(omx, omy, xpos, 121, 0xFFFF);
      tft.drawLine(osx, osy, xpos, 121, 0xF800);
      tft.fillCircle(xpos, 121, 3, 0xF800);
      tft.setCursor(xpos-27, 50);
      tft.setTextSize(2);
      tft.print("Glucoxy");

  // Draw MINI clock face "SECOND"
  tft.drawCircle(xpos, 155, 20, 0xFFE0);
  tft.drawCircle(xpos, 155, 18, 0x001F);
  tft.drawCircle(xpos, 155, 17, 0x07FF);
  tft.drawCircle(xpos, 155, 16, 0x07FF);
  tft.fillRect(xpos-10, 149,22,15,0x0000); //erase
  if(ss<10){tft.setCursor(xpos-10, 149); tft.setTextSize(2);
  tft.print('0'); tft.setCursor(xpos+2, 149);}
  else{
  tft.setCursor(xpos-10, 149);}
  tft.setTextSize(2);
  tft.print(ss);
  // Draw MINI clock face "Minutes"
  tft.drawCircle(xpos+35, 117, 20, 0xFFE0);
  tft.drawCircle(xpos+35, 117, 18, 0x001F);
  tft.drawCircle(xpos+35, 117, 17, 0x07FF);
  tft.drawCircle(xpos+35, 117, 16, 0x07FF);
  tft.fillRect(xpos+25, 111,22,15, 0x0000); //erase
  if(mm<10){tft.setCursor(xpos+25, 111); tft.setTextSize(2);
  tft.print('0'); tft.setCursor(xpos+37, 111);}
  else{
  tft.setCursor(xpos+25, 111);}
  tft.println(mm);
  // Draw MINI clock face "Hour"
  tft.drawCircle(xpos-35, 117, 20, 0xFFE0);
  tft.drawCircle(xpos-35, 117, 18, 0x001F);
  tft.drawCircle(xpos-35, 117, 17, 0x07FF);
  tft.drawCircle(xpos-35, 117, 16, 0x07FF);
  tft.fillRect(xpos-45, 111,22,15,0x0000); //erase
  if(hh<10){tft.setCursor(xpos-45, 111); tft.setTextSize(2);
  tft.print('0'); tft.setCursor(xpos-33, 111);}
  else{
  tft.setCursor(xpos-45, 111);}
  tft.setTextSize(2);
  tft.print(hh);
  //tft.setCursor(xpos-65, 111);
  //tft.println(':');
  if (hh>=0 && hh<12) d='A'; else {d='P';}
  tft.drawRoundRect(xpos-14,72,29,21,5,0x07FF);
  tft.fillRect(xpos-11, 75,23,15,0x0000); //erase
  tft.setCursor(xpos-11, 75);
  tft.setTextSize(2);
  tft.print(d);
  tft.println('M');
  }
}
if (currentpage == '2')
{
    getPedo();
    TSPoint p = ts.getPoint();
    if (p.z > ts.pressureThreshhold)
    {
      p.x = map(p.x,TS_MAXX, TS_MINX ,0,320);
      p.y = map(p.y,TS_MAXY, TS_MINY ,0,480);
      if (p.x > 50 && p.x > 260 && p.y > 180 && p.y < 270 && buttonEnabled)
      {
         tft.fillScreen(0x0000);
         currentpage = '1';
         drawHomeScreen();
      }

   }
}
if (currentpage == '3')
{
     getGlucose();
     TSPoint p = ts.getPoint();
    if (p.z > ts.pressureThreshhold)
    {
      p.x = map(p.x,TS_MAXX, TS_MINX ,0,320);
      p.y = map(p.y,TS_MAXY, TS_MINY ,0,480);
      if (p.x > 50 && p.x > 260 && p.y > 180 && p.y < 270 && buttonEnabled)
      {
         tft.fillScreen(0x0000);
         currentpage = '1';
         drawHomeScreen();
       }
     }
}
if (currentpage == '4')
{
    getPulse();
    TSPoint p = ts.getPoint();
    if (p.z > ts.pressureThreshhold)
    {
      p.x = map(p.x,TS_MAXX, TS_MINX ,0,320);
      p.y = map(p.y,TS_MAXY, TS_MINY ,0,480);
      if (p.x > 50 && p.x > 260 && p.y > 180 && p.y < 270 && buttonEnabled)
      {
         tft.fillScreen(0x0000);
         currentpage = '1';
         drawHomeScreen();
      }
    }
}

}

void drawHomeScreen(){
  tft.fillScreen(0x0000);
  tft.drawRoundRect(0, 0, 319, 240, 8, 0xFFE0);     //Page border

  tft.fillRoundRect(60, 180, 200, 40, 8, 0x001F);
  tft.drawRoundRect(60, 180, 200, 40, 8, 0xFFE0);  //PEDO

  //tft.fillRoundRect(60, 130, 200, 40, 8, 0x001F);   //Glu
 // tft.drawRoundRect(60, 130, 200, 40, 8, 0xFFE0);

  tft.fillRoundRect(60, 80, 200, 40, 8, 0x001F);
  tft.drawRoundRect(60, 80, 200, 40, 8, 0xFFE0); //Pulse oxi and heart rate

  tft.setCursor(25, 20);
  tft.setTextSize(3);
  tft.setTextColor(0xFFFF);
  tft.print("Welcome Here..");
  tft.setCursor(25, 50);
  tft.setTextSize(2);
  tft.setTextColor(0xFFE0);
  tft.print("Choose Your Sensor");
  tft.setTextColor(0x0000);
  tft.setCursor(110, 195);
  tft.print("Pedometer");
  //tft.setCursor(80, 145);
  //tft.print("Glucose Sensor");
  tft.setCursor(80, 95);
  tft.print("Pulse Oximeter");
}
void drawPulseOxi()
{
  tft.setTextColor(0x0000);
  tft.fillRoundRect (60, 180, 200, 40, 8,0x0000);
  tft.setTextColor(0x001F);
  tft.drawRoundRect (10, 10, 60, 36, 8, 0x0000);
  tft.setCursor(18, 15);
  tft.setTextSize(3);
  //tft.fillScreen(0x0000);
  tft.print("<-" );
  tft.setCursor( 70, 18);
  //tft.fillScreen(0x0000);
  tft.setTextSize(1);
  tft.print("Back to Main Menu");
  tft.setCursor( 70, 18);
  tft.setTextSize(3);
  tft.print("Pulse Oximeter & Heart rate Sensor");
  tft.print("MAX30102");
  tft.setTextColor(0xFFFF);
  tft.drawLine(0,100,319,100, 0xFFFF);

  }
  void getPulse()
  {
    bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps
    for (byte i = 0 ; i < bufferLength ; i++)
   {
    while (particleSensor.available() == false) //do we have new data?
           particleSensor.check(); //Check the sensor for new data

    redBuffer[i] = particleSensor.getRed();
    irBuffer[i] = particleSensor.getIR();
    particleSensor.nextSample();
    Serial.print(F("red="));
    Serial.print(redBuffer[i], DEC);
    Serial.print(F(", ir="));
    Serial.println(irBuffer[i], DEC);
   }

  maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);

  while (1)
  {
    for (byte i = 25; i < 100; i++)
    {
      redBuffer[i - 25] = redBuffer[i];
      irBuffer[i - 25] = irBuffer[i];
    }

    for (byte i = 75; i < 100; i++)
    {
      while (particleSensor.available() == false) //do we have new data?
        particleSensor.check(); //Check the sensor for new data

      digitalWrite(readLED, !digitalRead(readLED)); //Blink onboard LED with every data read

      redBuffer[i] = particleSensor.getRed();
      irBuffer[i] = particleSensor.getIR();
      particleSensor.nextSample(); //We're finished with this sample so move to next sample

      //send samples and calculation result to terminal program through UART
      Serial.print(F("red="));
      Serial.print(redBuffer[i], DEC);
      Serial.print(F(", ir="));
      Serial.print(irBuffer[i], DEC);

      Serial.print(F(", HR="));
      Serial.print(heartRate, DEC);

      Serial.print(F(", HRvalid="));
      Serial.print(validHeartRate, DEC);

      Serial.print(F(", SPO2="));
      Serial.print(spo2, DEC);

      Serial.print(F(", SPO2Valid="));
      Serial.println(validSPO2, DEC);
    }

    //After gathering 25 new samples recalculate HR and SP02
     maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);
       tft.setCursor(77,20);
       tft.setTextColor(0x0000);
       tft.println("Oxygen level is:");
       tft.setCursor(77,23);
       tft.println(spo2);
       tft.setCursor(97,20);
       tft.setTextColor(0x0000);
       tft.println("Heart Rate is:");
       tft.setCursor(77,23);
       tft.println(heartRate);

}
}
void calibrate(){
  float sum = 0, sum1 = 0, sum2 = 0;
  for (int i = 0; i < 100; i++) {
    xval[i] = float(analogRead(xpin) - 345);
    sum = xval[i] + sum;
  }
  delay(100);
  xavg = sum / 100.0;
  Serial.println(xavg);
  for (int j = 0; j < 100; j++)
  {
    yval[j] = float(analogRead(ypin) - 346);
    sum1 = yval[j] + sum1;
  }
  yavg = sum1 / 100.0;
  Serial.println(yavg);
  delay(100);
  for (int q = 0; q < 100; q++)
  {
    zval[q] = float(analogRead(zpin) - 416);
    sum2 = zval[q] + sum2;
  }
  zavg = sum2 / 100.0;
  delay(100);
  Serial.println(zavg);

}
void getPedo(){
  int acc = 0;
  float totvect[100] = {0};
  float totave[100] = {0};
  float xaccl[100] = {0};
  float yaccl[100] = {0};
  float zaccl[100] = {0};
  for (int a = 0; a < 100; a++)
  {
    xaccl[a] = float(analogRead(xpin) - 345);
    delay(1);
    yaccl[a] = float(analogRead(ypin) - 346);
    delay(1);
    zaccl[a] = float(analogRead(zpin) - 416);
    delay(1);
    totvect[a] = sqrt(((xaccl[a] - xavg) * (xaccl[a] - xavg)) + ((yaccl[a] - yavg) * (yaccl[a] - yavg)) + ((zval[a] - zavg) * (zval[a] - zavg)));
    totave[a] = (totvect[a] + totvect[a - 1]) / 2 ;
    Serial.println("totave[a]");
    Serial.println(totave[a]);
    delay(100);
    if (totave[a] > threshold && flag == 0)
    {
      steps = steps + 1;
      flag = 1;
    }
    else if (totave[a] > threshold && flag == 1)
    {
      // Don't Count
    }
    if (totave[a] < threshold   && flag == 1)
    {
      flag = 0;
    }
    if (steps < 0) {
      steps = 0;
    }
    Serial.println('\n');
    Serial.print("steps: ");
    Serial.println(steps);
    delay(1000);

    tft.setCursor(77,10);
    tft.println("steps: ");
    tft.print(steps);

  }
  delay(1000);
}
void drawGlucose(){

}
void getGlucose(){

}

The problem I am facing here is that, when code is uploaded, then at start clock appear only for 2 sec then screen becomes white and nothing else is appeared on screen. Please point out my mistake in code given above. I give this code my full try but cannot get desired results.

Start removing stuff that isn't involved in demonstrating the problem.  The more you remove, the more likely you are to get help.


text:
HC-05 drops connection, then DC Motors won't stop moving 'forward'
This is my first post. I seek you guys' help with my problem. Basically, my project is a Mobile-App Bluetooth Controlled WheelChair. Everything's done except a minor problem comes out during testing. After connecting everything, the wheelchair moves accordingly to the code that I wrote. However, after a few sec/min, the HC-05 drops connection, and the wheelchair drives its own by moving forward. I hope you can understand what I am saying.
When I set the speed = 100. I think I did not face the issue as above (confirmed).
Hardware:
PowerBank
Arduino Uno
HC 05
MDD20A Motor Driver
X2 24V DC Motor
X2 12V Battery
//including the libraries
#include <SoftwareSerial.h> // TX RX software library for bluetooth

//Initializing pins for bluetooth Module
int bluetoothTx = 0; // bluetooth tx to 0 pin
int bluetoothRx = 1; // bluetooth rx to 1 pin
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

//Motor 1
int Motor1_Pin = 2;
int Enable1 = 3;

//Motor 2
int Motor2_Pin = 4;
int Enable2 = 5;

char command ; //variable to store the data
int velocity = 0; //Variable to control the speed of motor

void setup()
{
  //Set the baud rate of serial communication and bluetooth module at same rate.
  // Serial Setup
  Serial.begin(9600); // default communication rate of the HC-06 Bluetooth module;
  bluetooth.begin(9600);

  // Motor Setup
  pinMode(Motor1_Pin,OUTPUT);
  pinMode(Enable1,OUTPUT);
  pinMode(Motor2_Pin,OUTPUT);
  pinMode(Enable2,OUTPUT);

  //Setting the enable as HIGH.
  digitalWrite(Enable1, LOW);
  digitalWrite(Enable2, LOW);
}

void loop(){
  if(bluetooth.available() > 0){  //Checking if there is some data available or not
    command = bluetooth.read();   //Storing the data in the 'command' variable
    Serial.println(command);      //Printing it on the serial monitor

    //Change pin mode only if new command is different from previous.
    switch(command){
    case 'F':  //Moving the Car Forward
      analogWrite(Enable1, 175);
      analogWrite(Enable2, 175);
      digitalWrite(Motor1_Pin, HIGH);
      digitalWrite(Motor2_Pin, HIGH);
      break;
    case 'B':  //Moving the Car Backward
      analogWrite(Enable1, 175);
      analogWrite(Enable2, 175);
      digitalWrite(Motor1_Pin, LOW);
      digitalWrite(Motor2_Pin, LOW);
      break;
    case 'L':  //Moving the Car Left
      analogWrite(Enable1, 175);
      analogWrite(Enable2, 100);
      digitalWrite(Motor1_Pin, HIGH);
      digitalWrite(Motor2_Pin, LOW);
      break;
    case 'R':   //Moving the Car Right
      analogWrite(Enable2, 175);
      analogWrite(Enable1, 100);
      digitalWrite(Motor2_Pin, HIGH);
      digitalWrite(Motor1_Pin, LOW);
      break;
    case 'S':   //Stop
      analogWrite(Enable1, 0);
      analogWrite(Enable2, 0);
      digitalWrite(Motor1_Pin, 0);
      digitalWrite(Motor2_Pin, 0);
      break;
//    case 'I':  //Moving the Car Forward right
//      digitalWrite(Motor2_Pin2, LOW);
//      digitalWrite(Motor2_Pin1, LOW);
//      analogWrite(enable1, 0);
//      analogWrite(enable2, 0);
//      break;
//    case 'J':  //Moving the Car backward right
//      digitalWrite(Motor2_Pin2, LOW);
//      digitalWrite(Motor2_Pin1, LOW);
//      analogWrite(enable1, 0);
//      analogWrite(enable2, 0);
//      break;
//    case 'G':  //Moving the Car Forward left
//      digitalWrite(Motor2_Pin2, LOW);
//      digitalWrite(Motor2_Pin1, LOW);
//      analogWrite(enable1, 0);
//      analogWrite(enable2, 0);
//      break;
//    case 'H':  //Moving the Car backward left
//      digitalWrite(Motor2_Pin2, LOW);
//      digitalWrite(Motor2_Pin1, LOW);
//      analogWrite(enable1, 0);
//      analogWrite(enable2, 0);
//      break;
    break;

    //Controlling the Speed of Car
    default:  //Get velocity
      if(command=='q'){
        velocity = 255;  //Full velocity
        analogWrite(Enable2, velocity);
        analogWrite(Enable1, velocity);
      }
      else{
        //Chars '0' - '9' have an integer equivalence of 48 - 57, accordingly.
        if((command >= 48) && (command <= 57)){
          //Subtracting 48 changes the range from 48-57 to 0-9.
          //Multiplying by 25 changes the range from 0-9 to 0-225.
          velocity = (command - 48)*25;
          analogWrite(Enable2, velocity);
          analogWrite(Enable1, velocity);
        }
      }
      }
    }

  }

"HC-05 drops connection" Does this mean is no longer connected to the phone (I'm guessing)?  Or does it mean something else?

Yes, true. It has something to do with PWM. When I set the speed at 100, there is no issue with the HC-05 Connection. However, once I set the speed at 175, it doesn't go smoothly for too long until suddenly the HC-05 connection drops the connection and then the dc motor becomes malfunction and drives its own (like stuck at forward). Sorry late. I did not realize this small comment box.

You might try adding some capacitors near the VCC/GND on the HC-05.

I assume that you want the chair to stop if the connection is lost. Is the 'state' pin on your HC-05 implemented, and does it distinguish between connected and not-connected (or something else)? If it's the former you should be monitoring that state pin. Otherwise, your Arduino and the mobile app need to agree on an "Are you there?" protocol; a handshake that takes place every 0.5 sec or so (off the wall guess!), and if the chair controller hasn't got a response darn near immediately, it stops. If the mobile misses a response, it should send a 'stop' (a backup which might not be heard by the chair controller), and alert the operator.
It wouldn't be a half-bad idea to have a watchdog timer (in hardware) on the chair that stops the motors if the chair controller doesn't reset it on short intervals. The chair controller is software; software sometimes fails. You'd like to detect that in hardware in time to cut the drive to the chair before it hits an obstruction or drives into the street.


text:
Proper wiring for a HiLetgo DAC to Arduino
I have been having trouble finding any recourses for a DAC chip that I bought. It is the HiLetgo PCM5102 DCA.
https://www.amazon.com/gp/product/B07Q9K5MT8/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1
There are 6 ports to be routed. VIN, GND (I know these) LCK, DIN, BCK, SCK, but the rest are a mystery to me. The Adafruit version has tutorials online but I got this one because of the built in 3.5mm jack is what I really needed. Any and all help is greatly appreciated. Let me know if I need to post any other resources.
I am trying to read the audio data coming in from songs through the 3.5mm jack.
Here is the data sheet for the Adafruit version of the DCA with a 3.5mm audio jack
I am asking for help in reading audio data from the input jack.
https://cdn-learn.adafruit.com/downloads/pdf/adafruit-i2s-stereo-decoder-uda1334a.pdf

@jsotola Hi, I actually am having trouble finding a data sheet online. I purchased this on amazon, but the product does not appear on the official HiLetgo website. As for a question I am asking what pins the LCK, BCK, DIN, and SCK slots are to be routed to

if you cannot find a datasheet for the module, then look for a datasheet for the main IC that is used in the module

reading audio data from the input jack ... the pictures at amazon are quite clear ... the jack is not an input

A DAC (Digital to Analog Converter) is an output device. You cannot read a signal with it. So the 3.5mm jack is an output (for example for headphones). For reading you need an ADC (Analog to Digital Converter). Also you would need to bias the voltage. Normal audio voltages on such jacks will vary around 0V, also going negative, which an ADC will not simply read (unless it does the biasing internally).

You have tagged this question as 'arduino-uno'.  The board you are asking about uses an I2S interface, which AFAIK is not available on the Uno.


text:
ESP8266 not running when connected to 3V3
I have a simple code that uses a tactile button and ESP8266.  I have one wire going from GND to one leg and one wire going from D3 to the other leg.  Works perfectly.  When I start it up, I have write statements in setup() which show that it is starting up and working.
I wanted to switch to a Touch Sensor.  I added a wire from one of the 3V3 to the VCC of the sensor.  If I do this while the program is running it seems to work... (it recognizes when I touch the sensor).  However, if I reset the ESP, then it no longer runs.  I see nothing in the serial window.
I tried to narrow the problem down and here's where I'm at...

The ESP is connected via USB to the computer so I can look at the console window to track how it's running.
I have a wire connected to D3 and GND (but the ends aren't connected to anything).  I reset the ESP and I see in the console window that it is printing out the expected print statements in setup().
I add a wire to 3V3 (it is not connected to anything).  I reset the ESP and now no print statements are in the console window - so I believe it is not running.

Why?  I thought 3V3 was to connect to sensors to power them.  Not input to the ESP.  So what am I missing?
RESOLVED:  I randomly picked the wrong GPIO to use... I switched to D1 and it now works ok.


text:
How to implement Arduino NANO as a RS-232 to USB adapter (Or do I need a Arduino Mega?) For 3D printer comms
I have a PC upstairs running my 3D printing slicer program (Simplify 3D). In the basement, I have several USB-enable 3D printers. My PC upstairs has a USB-to-RS-232 serial adapter. The serial side of that USB-to-Serial adapter connects to the Serial port of a Moxa Nport 6150 RS232-to-Ethernet protocol adapter. I get those Moxa devices for free when they break at work and then fix them for a couple of dollars.
The other side of the Moxa connects to my home computer network router. In the basement I can plug another Moxa into an ethernet cable on my home network and the serial RS232 output I need to connect to the Micro-USB jack of the 3D printer. How can I use an Arduino Nano (or Uno or Mega if required) to convert the RS232 data to the USB input of my 3D printer?
So I have PC->(RS-232)->[MOXA(RS-232)->Moxa(Ethernet)]->Router->[Moxa(Ethernet)->Moxa(RS-232)]->[Arduino(RS-232)->Arduino(USB)]->3D Printer(USB)... How can I get the Arduino to do that function? Items within [ and ] brackets are single devices performing a protocol conversion.
I know people use Raspberry Pi's and a program called OctoPrint to remotely control their 3D printers but I get the Moxas for free and Uno's or Nanos are dirt cheap. RPi's are more expensive and for several 3D printers it can start adding up. Any ideas?

The Nano can't take RS-232: it takes logic-level serial. You will need some kind of level shifter, like the MAX232 chips.

Hmm.. something like that MAX232 chip is the part I replace in the MOXA's to fix them. If I took the serial output of the Moxa through a MAX232 chip, then the TTL serial to the RX and TX of the Arduino... that's where I get lost.

Or can I just connect the RX and TX TTL data from the MAX232 and connect it directly to the Micro-USB jack? I found a MicroUSB pinout diagram but it shows the data as "D+" and "D-". Not sure how that correlates to TX and RX. Also, somewhere I am going to have to set the baud rate of whatever does the conversion to the 115200 speed of my 3D printer. Thats also why I think I need a Microcontroller? But I can set the serial baud rate on the Printer-side Moxa to 115200, then send that RS232 to the MAX232 but now I need a UART chip to convert the RX and Tx to D+ and D- ? Is that right?

RX and TX directly to D+ and D- is a no go. Different protocol, different voltage levels and different functions of the pins.

This depends entirely on what protocol your 3D printer expects over its USB port.  When you plug in your 3D printer, what does it appear as?  A native USB device with its own device driver?  As a USB/RS-232 UART that presents a virtual COM port?  If the 3D printer is not controlled by RS-232 then this is hopeless, and it's hopeless anyway because it has its UART already hidden behind a USB converter, so you would need to send the USB frames and not the raw RS-232 data.  Needs more info.

If the printer is an RS-232 protocol with a built-in USB converter, then one solution would be to open up the 3D printer, hack the RS-232 signal off of the UART, and connect the moxa directly to the printer's internal RS-232 lines.  The arduino RS-232/USB converter only works one way - the USB is the host side, not the device side.

Its not as easy as you think. An Arduino will not be enough for connecting the USB of the 3D printer. The USB protocol is strictly divided into slaves and masters. A USB(us) has exactly one master, which totally controls, what the slave can do. The slave itself cannot do much of its own.
Your 3D printer is a USB slave device. That enables a USB master (like a computer) to control it. The Arduino is also a USB slave device. If you connect both, you have a USB connection without a master. Nothing will happen. So you need to implement a USB master on the Arduino, which can handle the UART communication; all in software. That is generally possible, but I wouldn't recommend it. Also you definitely need extra hardware, because D+ and D- on USB are also electrically totally different from the TTL lines RX and TX (and also from the RS232 lines). They work differentially. So you need extra hardware to do that.
The easiest way with an Arduino would be to buy a USB host shield. With that you may be able to build, what you want.
But I would dispute, if this really makes sense. The cheapest USB host shield for Arduino, that I could find at amazon is around 10€, plus the price for an Arduino and the hassle of getting it all to work. A RaspberryPi Zero W only costs 10€. If you don't want to use wifi, you can add a USB to Ethernet adapter. And depending on the used software and its installation you might even be able to handle multiple printers with only one Pi (I use the Repertier Server, which has the ability to control multiple printers, I think). (Though depending on the number of printers and the resulting load you might wanna step up the game to a full Pi4)

There might be an additional way, depending on your printers. The printers microcontroller board might break the TX and RX pins out for you. Then you could connect the Arduino to them, no need for USB in that case. But that might not be an option. If the used microcontroller has a direct USB interface, there are no RX and TX pins to break out.

There's not enough information to provide a general solution at this time. As chrisl rightly says, the 3D printers are expecting a connection from a host. That host connection depends on whether the USB-serial interface inside the printer is supported. These are typically FTDI or WCH (QinHeng) chips, and would need the appropriate system driver for each type. This would be hard to implement on a USB host shield for Arduino.
Most 3d printers are, in essence, an Arduino inside. The typical 8-bit controller on the vast majority of 3d printers uses a very similar ATMega microcontroller. Some newer machines use 32-bit ARM microcontrollers, which are typically 3.3 V logic compared to the Arduino's (typical) 5 V. To add a standard RS-232 port you'd need to find the RX, TX, GND and Vcc points on each printer controller board and connect the right pins of your RS-232 to TTL converter boards to those points. This would bypass the USB ports on the printers entirely.
You might experience issues with flow control and buffering with multiple ports sending from one PC and Serial-Network-Serial latency. Marlin-style Gcode printers (= most filament printers that aren't Makerbot or Flashforge, approximately) don't use flow control: the printer sends back ok when it's ready for the next command. If your serial ports send data too slowly, the printer will pause and print quality may suffer. 3d printers don't need a really fast serial connections (under 20 kbit/s per printer, if using Gcode) but they need the data when they're ready to print.
OctoPrint can be quite an expensive option. The minimum supported platform is a Raspberry Pi 3b+ (+ power supply, SD card, USB cable, case, ...) dedicated to each printer. While you can run a very cut-down OctoPrint on a Raspberry Pi Zero, the author does not recommend it, and you have to click through an Unsupported Configuration: Use at your own risk dialogue.

The Nano, like the Uno, has an onboard serial ↔ USB converter. If you
can get a logic level serial from the Moxa, then you can use the Nano to
convert that to USB:

Load a do-nothing sketch in the Nano
Connect the Moxa TX to the Nano's Tx through a 1 kΩ resistor, and the
Moxa RX to the Nano's RX.

Yes, the second step looks backwards. The reason is that the labels RX
and TX refer to the ATmega328P that runs your sketches on the Nano.
Internally, the pin labeled RX is connected (through a resistor) to the
TX pin of the serial ↔ USB converter, and this is thus the pin you want
to connect the Moxa's RX. And similarly for the pin label TX (it's the
RX of the onboard converter).
Step 1 is important because you do not want the 328P to open its
serial port. The resistor is needed for the short time when the 328P is
running the bootloader, and has its serial port open.

+1 Jumping RESET to GND is typically what I do, although putting the do-nothing sketch on there is a good idea also.  With it held in reset, the bootloader doesn't get an opportunity to play with the serial lines either.

That's great! So I already have some of these RS232 to TTL converter boards I bought from Amazon: https://smile.amazon.com/gp/product/B07PFB4MHR/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1 I can then take the TX from that converter board to the TX of the Nano (running something like the Blink sketch) and the RX from the converter board to the RX of the Nano and then connect the Mini-USB of the NANO to the Micro USB of my 3D printer.

@ABNormal connect the Mini-USB of the NANO to the Micro USB of my 3D printer. No, that can never work.  USB is a host-driven protocol.  You can't just connect two devices together at the business end without a host.

If we take the following configuration PC(only pseudo serial like by old laptops without USB) -> Arduino -> USB printer,
than all what is important is Arduino 'xxx.ino' pseudo ;) code:
//do all necessary setups
  initialize
(((( loop
//pc-->arduino
    oh, some bytes on serial     //Nano detect some activity on serial port
    I'm dividing that in commands,status and cargo. //Nano parse this stream and determine what to do with what.
    huh, now repack that in USB protocol and send out // most probably this are data an commands to sent to printer over USB with appropriate protocol
//Arduino-->printer
    hey printer, here is some feed for you //Nano announce upcoming data event
//printer --> Arduino
    thanks, want more input    // printer certainly react with acknowledge, (success or error) and request or not next data
//Arduino --> PC
    let's send some more, he like it //Nano request next data package from sender PC
))) //end loop         and repeat until all done

But somehow more detailed.
I hope you understand that this id ;) "humor/joke/nonsense" pseudo code that show only organization of data flow how to make some functions/procedures. The concrete usable code is up to you.
Once more, it shows only that is possible to do it with Arduino.
It is certainly needed more than 5 minutes to write the comment.
I'm not sure if CR/LF come through correctly but anyone that can write code  in C would be able to properly format this text and may be start filling the sections with real code

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Welcome to Stack Exchange! It will probably be more helpful, and get you more reputation, if you answer more recent questions. I imagine this question, from April 2021, is no longer particularly relevant to the OP.


text:
Force compiler to execute instructions sequentially?
Is there a way to force the Arduino compiler to compile individual commands sequentially?  Looking at the disassembly, lines of the assembly code for different C/Arduino commands are mixed.  I was thinking something like a dmb or dsb command in ARM assembly.  I realize it's done the way it is for timing optimization, but I would like to see if changing it fixes some other timing issues I'm having.  I'm working on an Arduino Zero.  Thanks!

You can use the optimize function attribute to change the compiler optimization level for an individual function. That's the closest you'll get.

optimize
The optimize attribute is used to specify that a function is to be compiled with different optimization options than specified on the command line. Arguments can either be numbers or strings. Numbers are assumed to be an optimization level. Strings that begin with O are assumed to be an optimization option, while other options are assumed to be used with a -f prefix. You can also use the #pragma GCC optimize pragma to set the optimization options that affect more than one function. See Function Specific Option Pragmas, for details about the #pragma GCC optimize pragma.
This attribute should be used for debugging purposes only. It is not suitable in production code.

E.g.,:
void __attribute__((optimize("O0"))) myFunction() {
    // ...
}

From what I saw, the default optimization option is -O0, which is also the lowest level of optimization.  Is that correct?  I didn't see one but I want to make sure, is there an option to disable this kind of timing optimization?

No. Simply because there isn't really a 1:1 relationship between C code and Assembly code. If you want specific instructions in a specific order you will have to write assembly code directly. However, instruction ordering is highly unlikely to be the cause of some unspecified errors you may be having. I suspect you are suffering from an XY Problem and need to step back and look at the problem, not your (probably incorrect) assumption about the cause.