Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Digital I/O

Using millis() Instead of delay()

Replace blocking delay() calls with millis() timing: blink without waiting, run several tasks at once, handle the 49-day rollover and build simple non-blocking state machines.

delay() is easy, and it is the reason many first projects feel sluggish. While delay(1000) runs, the board does nothing else: buttons are ignored, sensors are not read, a second LED cannot blink at its own rate. The solution is to never wait. Instead, ask "what time is it?" each pass through loop(), and act only when enough time has passed. The function that tells you the time is millis().

What millis() returns

millis() returns the number of milliseconds since the program began, as an unsigned long (32 bits). It is driven by a hardware timer that the core sets up for you, so it keeps counting while your code does other work. It rolls over to zero after about 49.7 days (2ยณยฒ ms). A sibling, micros(), counts microseconds and rolls over after about 71 minutes.

The pattern

C++
unsigned long previousMillis = 0;
const unsigned long interval = 1000;
bool ledOn = false;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  unsigned long now = millis();
  if (now - previousMillis >= interval) {
    previousMillis = now;          // remember when we acted
    ledOn = !ledOn;
    digitalWrite(LED_BUILTIN, ledOn);
  }
  // other work runs here, every pass, with no waiting
}

Each pass, subtract the time of the last action from the current time. When the difference reaches the interval, do the action and store the new time. Everything else in loop() keeps running thousands of times per second.

C Stand-in: two tasks at two rates with a simulated millis()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Two LEDs, two independent rhythms, and no blocking. With delay() this is not possible without ugly arithmetic.

Why subtraction survives rollover

You might write if (millis() >= previousMillis + interval). This breaks after rollover, because the sum overflows to a small number. The subtraction form millis() - previousMillis >= interval works with unsigned arithmetic, which wraps modulo 2ยณยฒ: even when millis() wrapped to a small value and previousMillis is near the maximum, the difference comes out right. Prove it with a smaller type, so you can see the wrap:

C Stand-in: unsigned subtraction survives rollover

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Here the addition form says "due" only by accident; with other numbers it fires early or never. Always write elapsed time as now - start, with all variables unsigned long.

A small timer helper

For many timers, a struct keeps things tidy. In real Arduino code you can use a C++ class; the logic is identical:

C Stand-in: a reusable non-blocking timer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The same code on a board is three lines: define a Timer class with a bool expired() method using millis().

State machines with millis()

Sequences such as a traffic light (green 4 s, yellow 1 s, red 4 s) are state machines. Keep a state variable and a time stamp; on each pass, check whether the current state's duration has ended and move to the next. Read-only sketch:

C++
enum State { GREEN, YELLOW, RED };
State state = GREEN;
unsigned long stateStart = 0;

unsigned long durationOf(State s) {
  return s == GREEN ? 4000 : (s == YELLOW ? 1000 : 4000);
}

void loop() {
  if (millis() - stateStart >= durationOf(state)) {
    state = (State)((state + 1) % 3);
    stateStart = millis();
    // set the three LEDs for the new state here
  }
  // read the pedestrian button here, always responsive
}
stateDiagram-v2
    [*] --> GREEN
    GREEN --> YELLOW: 4 s
    YELLOW --> RED: 1 s
    RED --> GREEN: 4 s

Figure: the traffic light as a state machine. Time in each state is measured with millis().

When delay() is fine

delay() is acceptable for very short waits (a few milliseconds, for example while a sensor converts), in sketches that do only one thing, and in setup(). Use delayMicroseconds() for sub-millisecond waits. The moment a sketch must stay responsive, switch to millis().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is delay() a problem in a responsive project?

    delay() blocks, so buttons and sensors are not read during the wait.
  2. 2. Which condition is rollover-safe?

    Unsigned subtraction wraps correctly, so the elapsed time stays right across rollover.
  3. 3. What type should variables holding millis() values have?

    millis() is a 32-bit unsigned value; int (16 bits on Uno) would overflow after 32 seconds.
  4. 4. After how long does millis() roll over?

    2^32 ms is about 49.7 days.

Summary

  • millis() gives elapsed milliseconds; compare now - previous >= interval to act on a schedule.
  • It lets several tasks run at different rates and keeps inputs responsive.
  • Use unsigned long variables and subtraction so rollover (after 49.7 days) is harmless.
  • State machines plus time stamps replace long delay() sequences.
  • Keep delay() for tiny waits and single-purpose sketches.

Next: Bit Manipulation and Direct Port Access