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.
Right
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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro