Find a course

Module 4: Programming Your ArduinoLesson 9 of 1214 min

Timing Without delay(): Using millis()

See why delay() blocks your program, then use millis() to blink LEDs, read sensors and respond to buttons at the same time without missing input.

Step 1 of 14Learn

The button that only worked sometimes

Nia's project blinks a warning light once per second and should sound a buzzer immediately when a button is pressed. In testing, the button responds only about half the time.

Her loop looks like this:

digitalWrite(LED_PIN, HIGH); delay(500);
digitalWrite(LED_PIN, LOW);  delay(500);
if (digitalRead(BTN) == LOW) tone(BUZZER, 1000, 200);

During each delay(500), the processor does nothing else. The button is checked for a split second once per second. A quick press that starts and ends inside a delay is never seen.

delay() is blocking: it stops the whole program. That's fine for Blink, but real projects do several things at once: blink a light, read a sensor, watch a button, update a display. For that you need a non-blocking approach.

The tool is millis(), which returns the number of milliseconds since the board started. It's like checking a clock on the wall instead of falling asleep for a set time. Your loop runs constantly, and each task asks: "Has enough time passed since I last did my thing?"

Step 2 of 14Learn

The millis() pattern

Here's Blink rewritten without delay:

const int LED_PIN = 13;
const unsigned long INTERVAL = 500;
unsigned long previous = 0;
bool ledOn = false;

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

void loop() {
  unsigned long now = millis();
  if (now - previous >= INTERVAL) {
    previous = now;
    ledOn = !ledOn;
    digitalWrite(LED_PIN, ledOn);
  }
  // other tasks run here, thousands of times per second
}

Each pass, the code checks whether 500 ms have passed since the last toggle. If yes, it records the new time and flips the LED. If not, it moves on immediately. Now the button check, a sensor read or a display update can sit below the if block and run constantly.

Three details matter:

  1. Use unsigned long for anything that stores millis(). An int overflows after about 32.8 seconds.
  2. Always write now − previous >= INTERVAL. This subtraction still works correctly when millis() wraps back to zero, which happens after about 49.7 days. Comparing now >= previous + INTERVAL breaks at the wrap.
  3. Each independent task gets its own previous variable and interval.

Step 3 of 14Practice · Fill in the blanks

Fill in the blanks

To check whether an interval has passed, the safe comparison is millis() − >= interval, and the time variables should be of type .

Step 4 of 14Diagram

One pass through a non-blocking loop()

One pass through a non-blocking loop()Cycle diagram: now = millis() → now − previous ≥ interval? → Run task, previous = now → Check button and other tasks.thousands ofpasses persecondnow = millis()now − previous≥ interval?Run task,previous = nowCheck buttonand other tasks

Tap a shape with to see more.

now = millis()

Read the clock once per pass.

now − previous ≥ interval?

If not, skip the task and move on immediately.

Run task, previous = now

Toggle the LED and restart the countdown.

Check button and other tasks

Because nothing waits, the button is checked on every pass.

Step 5 of 14Practice · Work it out

millis() returns an unsigned long that counts up to 232 − 1 milliseconds before wrapping to zero. About how many days is that? Round to one decimal place.

Step 6 of 14Learn

Two tasks at different speeds

The real payoff comes with several tasks. This sketch blinks an LED every 500 ms and reads a temperature sensor every 2 seconds, while checking a button on every pass:

unsigned long lastBlink = 0, lastRead = 0;

void loop() {
  unsigned long now = millis();

  if (now - lastBlink >= 500) {
    lastBlink = now;
    toggleLed();
  }
  if (now - lastRead >= 2000) {
    lastRead = now;
    Serial.println(readTemperature());
  }
  if (digitalRead(BTN) == LOW) {
    soundAlarm();          // checked constantly
  }
}

None of the tasks waits for the others. The loop may run 50,000 times between temperature readings, and the button is checked on every one of them.

This structure scales. Many projects grow into a loop with a dozen timed tasks, each with its own timer. It's the simplest form of cooperative multitasking: each task does a quick bit of work and returns, so everyone gets a turn. The one rule: no task may block for long. A single delay(1000) anywhere freezes all the others.

Step 7 of 14Timeline

Two tasks sharing the first two seconds

  1. 0 ms
    LED on, temperature read

    Both timers start together.

  2. 500 ms
    LED off

    The temperature task is not due yet, so it is skipped.

  3. 1,000 ms
    LED on
  4. 1,500 ms
    LED off
  5. 2,000 ms
    LED on, temperature read

    Both tasks fall due on the same pass.

  6. Every pass
    Button checked

    Between the timed events the loop still runs thousands of times, so a press is noticed within a millisecond.

Step 8 of 14Compare

delay() vs. millis()

Aspectdelay()millis() pattern
How it worksPauses the whole program for a set timeChecks the clock and moves on if it is not time yet
Other code during the waitNothing else runs (interrupts aside)Everything else keeps running
Code lengthVery shortA few more lines and a variable per task
Good forQuick tests, startup pauses, very simple sketchesAny project that must react to input while timing something
Typical bugMissed button presses, sluggish responseUsing int instead of unsigned long; forgetting to update the previous time

Step 9 of 14Note

Step 10 of 14Practice · Diagram

A plant-watering state machine

The pump is running right now. Which state is the sketch in?

Tap the shape that answers the question, then press Check.

A plant-watering state machineCycle diagram: IDLE → WATERING → WAITING.IDLEWATERINGWAITING
IDLE

Check soil moisture every few seconds. Too dry? Switch on the pump and go to WATERING.

WATERING

Pump on. After 5 seconds (measured with millis), switch it off and go to WAITING.

WAITING

Give the water 10 minutes to soak in, then return to IDLE.

Step 11 of 14Practice · True or false

In the millis() pattern, if you forget to set previous = now inside the if block, the task runs once after the interval and then on every loop pass after that.

Step 12 of 14Note

Step 13 of 14Practice · What would you do?

What would you do?

A greenhouse sketch reads a soil sensor every 10 minutes using delay(600000). The owner now wants a manual "water now" button. What should change?

Step 14 of 14Practice · Choose one

Which variable declaration is correct for storing the time a task last ran?