r/arduino • u/n_sh_44 • Oct 21 '26
Hot Tip! Tip: the rollover-safe way to write millis() timers (and a few gotchas)
This keeps coming up in help threads, so here's a short write-up of the non-blocking timer pattern and the mistakes I see most.
unsigned long last = 0;
const unsigned long interval = 500;
void loop() {
unsigned long now = millis();
if (now - last >= interval) {
last += interval; // or: last = now;
// do the thing
}
}1. Compare with subtraction, not addition. if (now - last >= interval) keeps working when millis() rolls over after about 49.7 days, because unsigned subtraction wraps correctly. if (now >= last + interval) breaks right at the rollover.
2. Use unsigned long for the stored time. If last is an int (16-bit on an Uno), it goes negative after about 32 seconds and the timing gets weird.
3. last += interval vs last = now. += keeps a steady cadence with no drift, which is nice for blinking or sampling at a fixed rate. last = now guarantees at least interval between runs, which is safer if loop() can stall longer than one interval (otherwise += fires several times back to back to catch up).
4. One timestamp per task. Each thing you want to time gets its own last and interval, and you never need delay() for any of them.
5. micros() works the same way. It rolls over after about 71 minutes, and on 16 MHz AVR boards its resolution is 4 µs.
Hope it saves someone a debugging session.

