A
Arduinoโ€ข4d ago
Mohamed87

Fixing Timing Drift in Non-Blocking Arduino LED Blink Code

This code, as you can see, allows two LEDs to flash with different delays. This code works correctly unless the initial values โ€‹โ€‹of timePrevious1 and 2 are different, for example, 0 and 500, the LED, with 0, remains lit all the time. I tried to see where the problem is by displaying the value of timeNow and timePrevious of the lit LED. I found that the timePrevious value is normally incremented by the wait value of this LED. Therefore, the variables work correctly, but the digitalWrite instruction responsible for lighting the LED does not work! CODE: #define LED1 3 #define LED2 4 unsigned long wait1 = 500 ; unsigned long wait2 = 500 ; unsigned long timePrevious1 = 500 ; unsigned long timePrevious2 = 0 ; int LEDState1 = LOW ; int LEDState2 = LOW ; void setup() { Serial.begin(115200) ; pinMode(LED1, OUTPUT); pinMode(LED2, OUTPUT);
} void loop() { unsigned long timeNow = millis() ; // LED1 if (timeNow - timePrevious1 > wait1) { if ( LEDState1 == LOW ){ LEDState1 = HIGH ; } else{ LEDState1 = LOW ; } digitalWrite(LED1, LEDState1) ; timePrevious1 += wait1 ; }
// LED2 Serial.print("TimeNow : ") ; Serial.println(timeNow) ; //Just to undrestand what's wrong
Serial.print("TimePrevious2 ๐Ÿ˜Š ; Serial.println(timePrevious2) ; if (timeNow - timePrevious2 > wait2) { if ( LEDState2 == LOW ){ LEDState2 = HIGH ; } else{ LEDState2 = LOW ; } digitalWrite(LED2, LEDState2) ; timePrevious2 += wait2 ; } } CAN SOMEONE HELP ME PLEASE
3 Replies
Mohamed87
Mohamed87OPโ€ข4d ago
green LED --> PIN 3. (LED 1) Bleu LED -->PIN 4 (LED 2)
Maverick
Maverickโ€ข4d ago
When you set timePrevious1 to 500, it is always greater than timeNow. So, when you subtract (timeNow - timePrevious1 ), the result is negative. An unsigned long will wrap around to it's maximum value in this case. So, the result is always greater than wait1. The end result is the LED turning on and off as fast as possible. To the human eye, it will appear as if the LED is always on.
Mohamed87
Mohamed87OPโ€ข4d ago
Got it, thanks a lot ๐ŸŒŸ

Did you find this page helpful?