Sub topic 6
Surviving `millis()` Rollover
The rollover problem
This chapter assumes that you know basic Arduino sketches, setup(), loop(), pinMode(), digitalRead(), digitalWrite(), if statements, and unsigned integer types.
millis() returns the number of milliseconds since the board started running the sketch. On common Arduino boards, this value has type unsigned long. It eventually reaches its maximum value and wraps back to zero. This event is called rollover.
On many 32-bit Arduino platforms, rollover happens after about 49.7 days:
4,294,967,295 milliseconds ≈ 49.7 daysA sketch that runs for a few minutes may never show the problem during testing. A device that runs continuously can encounter it in normal operation.
Use elapsed-time subtraction
Suppose a timer started when millis() returned 4,294,967,290. Five milliseconds later, the counter rolls over and returns 0.
The current time looks smaller than the start time, but five milliseconds have still elapsed. Unsigned arithmetic handles this correctly when you subtract the start time from the current time.
unsigned long startTime = millis();
const unsigned long TIMEOUT_MS = 1000;
if (millis() - startTime >= TIMEOUT_MS) {
// The timeout has elapsed.
}Both values are unsigned. The subtraction happens modulo the integer range, so it produces the correct elapsed duration across the rollover boundary.
Do not calculate a future deadline and compare the current time with it:
// Fragile across rollover.
if (millis() >= startTime + TIMEOUT_MS) {
// The timeout has elapsed.
}If startTime + TIMEOUT_MS wraps to a small number, the comparison can become true too early or false for much longer than expected.
Rollover-safe interval timing
The same rule works for a repeating action. This example blinks the built-in LED every 500 milliseconds without blocking loop():
const unsigned long BLINK_INTERVAL_MS = 500;
unsigned long previousMillis = 0;
bool ledState = LOW;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousMillis >= BLINK_INTERVAL_MS) {
previousMillis = now;
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
// Other work can run on every pass through loop().
}When rollover occurs, now - previousMillis still represents the time since the last action. The loop therefore continues blinking normally.
Assigning previousMillis = now measures each interval from the time the action actually ran. This is simple and prevents the code from running repeatedly to catch up if the loop was delayed.
For tasks that must maintain a precise schedule, use:
previousMillis += BLINK_INTERVAL_MS;That preserves the original schedule, but it can cause several immediate executions after a long delay. Choose the version that matches the behavior you need.
Limits and common mistakes
Subtraction cannot tell the difference between one short interval and a duration that has wrapped around more than once. Therefore, do not use one timestamp comparison to measure intervals approaching the full rollover period. In practice, keep individual timeouts comfortably below the rollover period.
Avoid these mistakes:
- Store
millis()in a signed type such aslong. - Cast timestamps to floating-point values.
- Compare
millis()directly withstart + timeout. - Test only short runs and assume a continuously running device is safe.
- Use a timeout so long that the counter could wrap more than once.
The safe pattern is:
Exercise
Why can millis() >= startTime + timeout fail after rollover, and what expression should replace it?
Show answer
The future deadline can wrap to a small number, making the comparison incorrect. Use millis() - startTime >= timeout with unsigned timestamp and duration variables.