Peter_n:
aarg, to avoid the rollover problem, it is necessary to use "unsigned long" and timestamp the current moment. That way the "millis() - prevMillis" is always a positive number and that prevents the rollover problem.
When for example the time in the future is remembered, millis() could be higher or lower than that value, and that is not possible with unsigned long.
Here is an example that shows what it is like to use unsigned variables that rollover : Arduino Playground - TimingRollover
There is something about this that is fishy. I modified that code to show a little more of the results of the arithmetic and comparisons. The idea behind it is to use byte to simulate unsigned time. I am giving a snippet here because a link is already provided to the source.
p = 4; // rollover of value 260
q = 250;
r = p - q; // valid for unsigned variables
Serial.println( F("260 (=4) - 250 = "));
Serial.println( r, DEC);
Serial.println( r < 10);
Serial.println( p-q, DEC);
Serial.println( p-q < 10);
which produces this:
260 (=4) - 250 =
10
0
-246
1
Notice that unless an assignment is made to a byte, the value is incorrect.
But! This form of comparison seems like the comparison of long ints in the actual blink code that follows, the structure of which we are all so familiar:
if ( ul_CurrentMillis - ul_PreviousMillis > ul_Interval)
It seems to me, that if the analogy to the byte example is valid, this expression should fail, as it did with
( p-q < 10)
above.
I'm just not quite buying into this at the moment. Something is wrong. For sure, it could be the way I'm seeing it, but I'm not sure how.
I modified the unsigned long portion of the test in an identical way:
ulNew = 705032704UL; // rollover of value 5,000,000,000
ulOld = 4000000000UL;
ul = ulNew - ulOld; // valid for unsigned long
Serial.println( F("5,000,000,000 (=705,032,704) - 4,000,000,000 = "));
Serial.println( ul, DEC);
Serial.println( ul < 1000000000);
Serial.println( ulNew - ulOld, DEC);
Serial.println( ulNew - ulOld < 1000000000);
and the result is more encouraging:
Test with unsigned long.
3,000,000,000 - 2,000,000,000 = 1000000000
5,000,000,000 (=705,032,704) - 4,000,000,000 =
1000000000
0
1000000000
0
What is so "special" about the unsigned long comparison, that made it work, while the other unsigned data type, byte, didn't?