Skip to content

Arduino Alternative to delay() Not Working

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about Arduino Alternative to delay() Not Working. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Replacing delay() with millis() timing does not produce the expected behavior.

Quick Fix

Wrong

unsigned long prev = millis();
void loop() {
  if (millis() - prev == 1000) {  // Rarely exactly equal
    action();
  }
}
action() rarely or never executes.
unsigned long prev = 0;
const unsigned long interval = 1000;

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
  unsigned long now = millis();
  if (now - prev >= interval) {
    prev = now;
    digitalWrite(13, !digitalRead(13));
    Serial.println("Toggled");
  }
}
LED toggles every second. "Toggled" prints each time.

Prevention

Use >= (greater-or-equal) not == for millis() comparisons. millis() increments by ~1 and may skip the exact target value. Initialize prev = 0 (not millis()) so the first interval starts immediately. The substraction pattern handles overflow correctly.

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

FAQ

### Why use >= instead of ==?

millis() skips values (increments by ~1 each ms). The exact comparison target may be missed. >= catches any value at or past the target.

Should I use unsigned long or long?

Always unsigned long for millis(). Unsigned overflow wraps to 0, which the subtraction pattern handles. Signed overflow is undefined behavior.

What if I need multiple timers?

Use multiple prev variables, one per timer. Or use an array of structs for many timers. Each has its own interval and prev value.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro