ENع
←Non-blocking code
Lesson 18 · Interrupts, timers and PWM

Non-blocking code: replacing delay()

12 min9 steps5 questionsIntermediate
About this lesson

delay() parks the CPU on one line, so every other job in loop() stops with it. Follow an Arduino Uno with two jobs: blink the LED on pin 13 every 500 ms, and light the LED on pin 12 while a button on pin 2 is held. With delay(), a press from 1,200 to 1,450 ms is never seen. Then rewrite loop() so it never waits: each pass reads millis(), does only what is due, and reads the button every time. The lesson “Hardware timers, prescalers and millis()” explains where millis() comes from; here you use it to structure your firmware.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 18 · Interactive
01 / 09

Two jobs, one loop()

Our Arduino Uno has two jobs. Blink the LED on pin 13 every 500 ms. And light the LED on pin 12 while you hold the button on pin 2. Both jobs must keep going at the same time.

board   Arduino Uno R3, ATmega328P at 16 MHz
job 1   pin 13: flip every 500 ms
job 2   pin 12 = button held?
button  pin 2 to GND, INPUT_PULLUP
        held -> LOW, open -> HIGH
Loading figure…
or ← →
Read the lesson step by step
  1. Two jobs, one loop()

    Our Arduino Uno has two jobs. Blink the LED on pin 13 every 500 ms. And light the LED on pin 12 while you hold the button on pin 2. Both jobs must keep going at the same time.

    board   Arduino Uno R3, ATmega328P at 16 MHz
    job 1   pin 13: flip every 500 ms
    job 2   pin 12 = button held?
    button  pin 2 to GND, INPUT_PULLUP
            held -> LOW, open -> HIGH
  2. delay() makes the CPU wait

    The easy way uses delay(). delay(500) pauses the program for 500 ms. The CPU sits on that line and does nothing else: no reading pins, no maths, no writing pins. Only interrupts still run.

    line 1  pin 13 HIGH, LED on         t = 0 ms
    line 2  delay(500)                   t = 0 .. 500 ms
            the CPU stays on this line
            interrupts still run (millis keeps counting)
            no other line of loop() runs
  3. A press nobody sees

    At 1,200 ms you press the button, and you let go at 1,450 ms. The CPU is inside a delay(500) the whole time, so it never looks. The press comes and goes, and LED 12 stays dark.

    pass 2  line 1 at 1,000 ms, line 2 waits until 1,500 ms
    press   1,200 .. 1,450 ms   (250 ms)
    reads   line 5 runs at 1,000, 2,000, 3,000 ms
    seen    never
  4. One look per second

    This loop reads the button only once per pass, on line 5, and a pass takes 1,000 ms. Short presses vanish, and long ones wait up to a second. Every delay you add makes it worse.

    one pass   500 + 500 = 1,000 ms of waiting
    line 5     reads pin 2 once per pass
               at 2,000 ms: HIGH (released), LED 12 off
    worst wait almost 1,000 ms
    missed     any press shorter than one pass can vanish
  5. Check the clock, never wait

    The fix: never wait. Each pass starts with now = millis(), the milliseconds since the board started. A pass with no waiting is very short, so loop() comes round again almost at once, thousands of times a second.

    line 1  now = millis();      read the clock, no waiting
    16 MHz  most instructions take 1 cycle = 62.5 ns
    even 1,000 instructions = 62.5 µs per pass
            = about 16,000 passes a second
    (the figure is slowed down a great deal)
  6. Not time yet? Move on

    Line 2 asks: have 500 ms passed since last? At now = 1,130, now - last is 130, so no. The CPU skips the LED code, reads the button on line 7, sets LED 12 on line 8, and starts the next pass.

    now  = 1,130
    last = 1,000      (set at the flip at 1,000 ms)
    line 2  1,130 - 1,000 = 130 >= 500?  false
    skip    lines 3 .. 5
    line 7  read the button, line 8 set LED 12
  7. The press is seen at once

    You press at 1,200 ms. The very next pass reaches line 7 and reads LOW, which means held. Line 8 turns LED 12 on, microseconds after your press. Nothing is missed, because nothing waits.

    press   1,200 ms, pin 2 goes LOW
    line 7  b = LOW (0)
    line 8  digitalWrite(12, !b)  ->  HIGH, LED on
    release 1,450 ms: the next pass turns it off
    delay version: this press was never seen
  8. Time is up: flip the LED

    At now = 1,500, now - last is 500, so line 2 is true. last becomes 1,500, the LED state flips, and line 5 turns LED 13 on. Then the pass carries on and reads the button as usual.

    line 2  1,500 - 1,000 = 500 >= 500   true
    line 3  last = 1,000 + 500 = 1,500
    line 4  led = true
    line 5  pin 13 HIGH, LED on
    next    true again at 2,000 ms
  9. Keep every pass short

    Give every timed job its own last and interval, and check it on each pass. Never wait inside a pass: no delay(), no while loop waiting for a pin. The lesson “Event-driven firmware as a state machine” builds on this.

    per job   unsigned long last; const interval;
              if (now - last >= interval) { ... }
    never     delay(...)  inside loop()
              while (digitalRead(2) == HIGH) {}
    
    // Arduino Uno R3: blink pin 13 every 500 ms and
    // light pin 12 while the button on pin 2 is held
    unsigned long last = 0;
    bool led = false;
    
    void setup() {
      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(2, INPUT_PULLUP);  // pressed reads LOW
    }
    
    void loop() {
      unsigned long now = millis();
      if (now - last >= 500) {
        last += 500;
        led = !led;
        digitalWrite(13, led);
      }
      int b = digitalRead(2);
      digitalWrite(12, !b);
    }

Quiz Unlocks after the last step.