Skip to content

Ard Millis Elapsed

DodaTech 1 min read

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

The Problem

millis() does not give the correct elapsed time between events.

Quick Fix

Wrong

unsigned long start = millis();
delay(1000);
unsigned long elapsed = millis() - start;  // OK but blocking
delay() wastes CPU time. Other tasks cannot run.
unsigned long prevTime = 0;
const unsigned long interval = 1000;

void loop() {
  unsigned long now = millis();
  if (now - prevTime >= interval) {
    prevTime = now;
    Serial.print("Elapsed: ");
    Serial.println(now / 1000);
  }
  // Other non-blocking tasks here
  checkSensor();
  updateDisplay();
}
"Elapsed: 1", "Elapsed: 2", ... every second, non-blocking.

Prevention

Use millis()-start for non-blocking timing. The subtraction pattern works correctly with unsigned long overflow. For microsecond precision, use micros() โ€” but its resolution is 4 ยตs on 16 MHz AVR. millis() resolution is 1.024 ms on AVR (Timer0 prescaler 64).

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

FAQ

### What is the resolution of millis()?

1.024 ms on 16 MHz standard Arduino boards. It increments every 1024 ยตs due to the Timer0 prescaler of 64.

How accurate is millis()?

~0.5% typical error due to ceramic resonator tolerance. Temperature and voltage cause additional drift. For precise timing, use an RTC module (DS3231).

Does millis() work during interrupts?

millis() uses Timer0 interrupt to increment. If interrupts are disabled too long, millis() will skip ticks.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro