Sub topic 6
Surviving millis() rollover
This chapter assumes you can write a non-blocking millis() interval like the one in the previous chapter, and that you know unsigned long is a 32-bit unsigned integer on most Arduino boards. Here you will see what happens when the millis() counter reaches its maximum value and wraps to zero. You will also learn why one way of writing the comparison keeps working and another does not.
What rolls over, and when
millis() returns the number of milliseconds since the board started running the sketch. It returns an unsigned long, which holds values from 0 to 4,294,967,295 (2^32 − 1). One millisecond after 4,294,967,295 the counter goes back to 0. This is called rollover or wraparound.
At one count per millisecond, that takes about 49 days, 17 hours, 2 minutes and 47 seconds. A sketch that runs on a desk for an afternoon never sees it. A sketch that controls a pump, a door sensor or a data logger can run for months, so it will.
Other counters wrap much sooner:
| Counter | Type | Wraps after |
|---|---|---|
| `millis()` | `unsigned long` (32 bits) | about 49.7 days |
| `micros()` | `unsigned long` (32 bits) | about 71.6 minutes |
| A timestamp stored in `unsigned int` on an AVR board such as the Uno | 16 bits | 65.536 seconds |
| A timestamp stored in `byte` | 8 bits | 256 ms |
The last two rows are not features of the clock. They come from storing a timestamp in a variable that is too narrow. Section "Common errors" covers them.
Why unsigned subtraction survives
Unsigned integers in C++ use modular arithmetic. A 32-bit unsigned value that goes below 0 or above 4,294,967,295 wraps around, and this behavior is defined by the language. Subtraction therefore gives the distance travelled forward on a circle of 2^32 positions, no matter where the wrap point lies.
Take a small counter that wraps at 256, to keep the numbers short. You record start = 250. Ten ticks later the counter reads 4, because it passed 255 and wrapped. Then 4 − 250 = −246, and in modular arithmetic −246 is the same as −246 + 256 = 10. The answer is the real elapsed time. A 32-bit unsigned long does the same with 2^32 in place of 256.
So this expression is correct at any moment, wrap or no wrap:
if (millis() - startTime >= timeout) {
// at least `timeout` ms have passed since startTime
}The result is right as long as two conditions hold:
startTime, the result andtimeoutare allunsigned long(or another type at least as wide as the counter).- The real elapsed time is less than 2^32 ms. Past that point the circle has been fully traversed and the arithmetic cannot tell 5 ms from 49.7 days plus 5 ms. In practice, you must check the timeout at least once every 49 days, which
loop()does continuously.
Worked numbers
Suppose you record startTime 300 ms before the counter wraps, and the timeout is 500 ms.
The 300 ms before the wrap plus the 200 ms after it add up to the 500 ms that really passed. The subtraction recovers that number without special handling.
Comparing a safe and a fragile test
A common alternative is to compute a deadline once and compare the clock against it:
unsigned long deadline = millis() + timeout;
// later:
if (millis() >= deadline) { ... }This works until millis() + timeout crosses the wrap point. With startTime = 4294966996 and timeout = 500, the sum is 4294967496. That does not fit in 32 bits, so it wraps to 200. Now deadline is 200, and millis() >= 200 is already true because millis() currently reads about 4.29 billion. The timeout fires immediately instead of after 500 ms. After the clock itself wraps, the comparison behaves differently again, which makes the bug hard to reproduce.
You can check both tests without waiting 49 days. The sketch below passes the clock value in as a parameter, so you can feed it values around the wrap point.
const unsigned long TIMEOUT_MS = 500;
const unsigned long START_MS = 0xFFFFFED4UL; // 300 ms before the counter wraps
bool elapsedSafe(unsigned long now, unsigned long start, unsigned long timeout) {
return now - start >= timeout;
}
bool deadlineFragile(unsigned long now, unsigned long start, unsigned long timeout) {
return now >= start + timeout;
}
void setup() {
Serial.begin(9600);
const unsigned long offsets[] = {0, 100, 499, 500, 600};
for (int i = 0; i < 5; i++) {
unsigned long now = START_MS + offsets[i]; // wraps past 2^32 like millis()
Serial.print("offset=");
Serial.print(offsets[i]);
Serial.print(" now=");
Serial.print(now);
Serial.print(" safe=");
Serial.print(elapsedSafe(now, START_MS, TIMEOUT_MS) ? "yes" : "no");
Serial.print(" fragile=");
Serial.println(deadlineFragile(now, START_MS, TIMEOUT_MS) ? "yes" : "no");
}
}
void loop() {
}Open the Serial Monitor at 9600 baud. You should see the following results. The first column is the real time since START_MS, so the timeout should read "yes" only from 500 ms onward.
| Real elapsed (ms) | `now` | `safe` | `fragile` | Correct answer |
|---|---|---|---|---|
| 0 | 4294966996 | no | yes | no |
| 100 | 4294967096 | no | yes | no |
| 499 | 199 | no | no | no |
| 500 | 200 | yes | yes | yes |
| 600 | 300 | yes | yes | yes |
The safe test matches the correct column on every row. The fragile test reports a timeout at 0 ms and 100 ms, long before it should.
This technique is also how you test your own code. Move the starting value close to 2^32 and confirm the behavior. If your timing logic is written as functions that take now as an argument, you can test the wrap without touching the hardware clock.
Common errors
Storing timestamps in a narrow type. On a 16-bit-int board such as the Uno, this code looks harmless:
unsigned int lastTime = millis(); // keeps only the low 16 bitsThe assignment silently discards the upper 16 bits. Later, millis() - lastTime mixes the full 32-bit clock with a truncated 16-bit value, and the result is wrong once millis() passes 65,535. Declare every timestamp as unsigned long (or uint32_t). The compiler normally does not warn about this.
Using a signed type. long lastTime holds the same bits as an unsigned value, but mixing signed and unsigned operands in comparisons is a classic source of surprises. Use unsigned long for timestamps and intervals alike.
Plain int constants that overflow. On AVR boards, int has 16 bits, so 60 * 1000 is computed as an int and overflows before it is ever stored in your unsigned long. Add the UL suffix so the arithmetic is done in 32 bits:
const unsigned long ONE_MINUTE_MS = 60UL * 1000UL;
const unsigned long ONE_DAY_MS = 24UL * 60UL * 60UL * 1000UL;Using a stale now with a newer timestamp. Suppose loop() reads now = millis() and then something updates a timestamp with a later reading, for example an interrupt handler. Then now - timestamp goes negative and wraps to a number near 4.29 billion, which passes any "at least N ms" test. Capture now once per pass and compare against values set no later than that, or re-read millis() at the point of comparison when an interrupt can set the timestamp. The interrupt chapter returns to this.
Intervals that are too long. The subtraction cannot distinguish elapsed times that differ by exactly 2^32 ms. A timeout of more than 49 days will not work with millis() alone. Count in a larger unit, such as minutes or days, with a second variable when you need that range.
Keeping the interval drift-free
The blinking sketch in the previous chapter sets previousMillis = now each time the interval elapses. That makes the period slightly longer than INTERVAL_MS, because the loop usually notices the interval a little after it ended. If you need an exact average rate, add the interval instead:
const unsigned long INTERVAL_MS = 500;
unsigned long previousMillis = 0;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
if (millis() - previousMillis >= INTERVAL_MS) {
previousMillis += INTERVAL_MS; // keeps the schedule anchored, so errors do not accumulate
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
}Adding to an unsigned variable also wraps cleanly, so this version is rollover-safe. It has one limit: if the loop stalls for several intervals, for example during a long delay() or a slow serial call, the block runs repeatedly until previousMillis catches up. For a debounce timer, where you want "the time since the last change", assign the current time as before.
Summary of rules
- Store timestamps and intervals as
unsigned long. - Test for elapsed time with
millis() - start >= interval. - Use
ULon constants that can exceed 32,767 when multiplied. - Do not compute deadlines as
start + intervaland compare them with>=. - Keep intervals shorter than 2^32 ms, and keep checking at least that often.
- Test wrap behavior by feeding the logic a starting value just below 2^32.
Exercise
A sketch declares unsigned long start = 4294967000UL; and checks millis() - start >= 1000UL. The first time millis() reads 704 after the wrap, what is millis() - start, and does the check pass?
Show answer
The counter went from 4294967000 up to 4294967295 (295 ms), then one more ms to reach 0, then 704 ms more, so 4294967296 − 4294967000 + 704 = 296 + 704 = 1000 ms. In modular arithmetic 704 − 4294967000 wraps to 1000, so the check passes at exactly that moment.
Exercise
A student writes unsigned int lastTime = millis(); on an Uno and later tests millis() - lastTime >= 2000. After about 70 seconds of uptime, the test fires at the wrong moments. Why, and what is the fix?
Show answer
unsigned int is 16 bits on the Uno, so lastTime keeps only the low 16 bits of millis() (it wraps every 65.536 s). The subtraction then compares a full 32-bit clock against a truncated value, so the result no longer equals the real elapsed time. Declaring lastTime as unsigned long fixes it.