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:01 here 1 − 12:00 ≡ 0:01= 1).
Added some basic information about modular arithmetic because it seem crucial for understanding why the solution provided actually works.
Edgar Bonet
- 45.2k
- 4
- 42
- 81