Normal if we want to run some code in fixed interval, we will use the following pattern:
void loop() {
// check if the fixed interval reached
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
//do something in fixed interval
//...
}
}
It's a general practice as show in Arduino BlinkWithoutDelay example.Where millis() returns the number of milliseconds passed since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 50 days.
So, what will happen if it overflow? Will it be a bug in the statement (currentMillis - previousMillis >= interval)?
The answer is NO.
Lets try the following example, run on Uno.
void setup() {
Serial.begin(9600);
while (!Serial) {
} // wait for serial port to connect.
unsigned long i =0;
unsigned long j = i-1;
unsigned long k = j+1000;
Serial.print("i = ");
Serial.println(i);
Serial.print("j = ");
Serial.println(j);
Serial.print("k = ");
Serial.println(k);
Serial.print("(k > j) : ");
Serial.println((k > j) ? "true" : "false");
Serial.print("k-j : ");
Serial.println(k-j);
Serial.print("((k-j) >= 1000) : ");
Serial.println(((k-j) >= 1000) ? "true" : "false");
}
void loop() {
// put your main code here, to run repeatedly:
}