Skip to content

Ard Millis Timing

DodaTech 1 min read

In this tutorial, you'll learn about Arduino millis() Timing Drifts Over Time. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Using millis() for timing produces cumulative drift.

Quick Fix

Wrong

if (millis() % 1000 == 0) {  // Rarely true!
  action();
}
action() almost never executes because millis() skips that exact value.
unsigned long prev = 0;

void loop() {
  unsigned long now = millis();
  if (now - prev >= 1000) {
    prev += 1000;  // Fixed interval — no drift
    action();
  }
}
action() fires at exactly 1-second intervals with no cumulative drift.

Prevention

Use prev += interval (fixed-step) instead of prev = now to avoid drift. The fixed-step approach maintains the original phase. For absolute time, use an RTC. millis() accuracy depends on the board's clock source — ceramic resonators drift with temperature.

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

FAQ

### Why does prev = now cause drift?

The time spent in action() and loop() adds to each interval. Over many cycles, the drift accumulates. prev += interval skips that overhead.

How much drift is normal?

Ceramic resonator: ~0.5% drift (5 seconds per 1000). Crystal oscillator (Uno R3 improved): ~0.005%. External RTC: <0.001%.

Can I compensate for drift?

Yes. Measure actual drift over an hour and adjust the interval. Or use an RTC module for <1 ppm accuracy.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro