To reset or not to reset? millis rollover is the question

18,446,744,069,414,584,432 = 0xFFFFFFFF00000070

We can only have 4 bytes, therefore:

0x70 = 112 decimal

How did you get that number?? My calculator doesn't give me that...
Is there a special way of doing this math?


Assume millis( ) returns 96
Assume lastMillis = 4294967280

What happens ?

I don't have any apple devices, so I can't use that app.

I have no idea what would happen.

if(millis() - lastMillis >= 112)
Our math says we get:
millis( ) - lastMillis gave us 112

if( 112 >= 112) this is true, therefore we will reset the TIMER and toggle the pin 13 state.

i.e.

lastMillis = millis(); i.e. lastMillis = 96
And
digitalWrite(13, !digitalRead(13)); //toggle pin 13


We have a TIMER that toggles pin 13 every 112 milliseconds and we have proven an overflow on millis( ) makes no difference.

How? When it overflows back to 0, won't it then have one blink that isn't the correct length? That isn't crucial for a blinking LED, but won't that be bad if we are doing something a whole lot more precise than that?

In our example not only did millis( ) overflow it even went past 0 (zero) by 96.

The assumption was millis( ) returned 96, it overflowed and is now sitting at 96 when our sketch ran the if( ) statement.

1 Like

It is crucial you understand this technique if you want to write effective none blocking sketches that contain TIMERS.

2 Likes

The code below toggles pin 13 every 1 second, there is no problem due to an overflow in millis( )


unsigned long lastMillis;

. . .

if(millis() - lastMillis >= 1000)
{
   lastMillis = millis();

   digitalWrite(13, !digitalRead(13));
}

1 Like

Absolutely not.  Do all the math with unsigned numbers.

Maybe a graphic will help.

Yes

  • And that’s the crux to all of this, unsigned math.
1 Like

@outbackhut
This calculations proves that everyone who writes about the need to reset mills is wrong. They simply do not understand unsigned arithmetic.

2 Likes

Unsigned two's complement arithmetic.

While it is now uncommon to cross paths with hardware that uses anything else the "two's complement" bit makes searching the internet much more efficient and productive.

I suspect starting with a three or four bit number will make the subject easier to explain. That would make demonstrating "long subtraction" palatable.

So you are saying length matters ?

Noooo! It's just easier to understand if the number is shorter. The link in post #7 is the best explanation I have found.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.