I wondered what will happen if I let an unsigned long integer overflow and subtract something from it.
This is something what people usually do to create a 'timer'.
For simplicity I didn't use millis(), instead of that I just used a long unsigned integer.
When I run the code, something strange happens after a few seconds (usually when the time difference was 61). Please run the code and have a look yourself. And even more strange, sometimes it happens after a different time span after reset.
Can anyone explain this? The sketch is running on an Arduino Uno.
unsigned long timehelp1 = 4294967293; //unsigned long just before it overflows
unsigned long timehelp2 = 4294967290;
unsigned long prev_time;
void setup() {
Serial.begin(115200);
prev_time = millis();
}
void loop() {
//do something every second
if (millis() - prev_time >= 1000)
{prev_time = millis(); doit();}
}
void doit()
{
timehelp1 = timehelp1 + 1;
Serial.print("Millis: "); Serial.print(timehelp1); Serial.print(" "); Serial.print("Difference: "); Serial.println(timehelp1 - timehelp2);
}
This code will give the correct result even if millis() overflows
if (millis() - prevTime >= interval) {
assuming prevTime and interval are unsigned long.
If you just want to experiment with the effect of rollover using unsigned integer maths it will be much simpler with byte variables as they roll over after 255 steps
@Robin2: I was just experimenting and I don't understand why I get the strange behaviour with my code
@sterretje: well, the timehelp1 variable is counting up to 4294967295, then it overflows and goes to 0, it counts up tp 55 and then suddenly jumps to 4294967294, then to 4294967295, and then of course to 0 again.
And sometimes it doesn't even cout up to 55 but just to 27 or another value before jumping to 4294967294....