ENع
←Firmware state machines
Lesson 19 · Interrupts, timers and PWM

Event-driven firmware as a state machine

12 min10 steps5 questionsIntermediate
About this lesson

Firmware that reacts to buttons and to time gets tangled fast if it is written as a list of steps with delay() and flags. A state machine fixes that: name the few situations the device can be in (states), name what can happen (events), and write one rule for each arrow between them. Build a stair light on an Arduino Uno R3, with a button on pin 2 and the LED on pin 13: three states, two events, five arrows, and a loop() that never waits. The Hardware lesson “State machines” covers state diagrams and Moore and Mealy machines; “Non-blocking code: replacing delay()” covers the millis() timing used here.

You'll learn to

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

Fig 19 · Interactive
01 / 10

The job: a stair light

A stair light on an Arduino Uno R3. Press the button on pin 2 and the LED on pin 13 comes on. After 10 s it blinks for 3 s as a warning, then goes off. A press while it blinks keeps it on.

board     Arduino Uno R3 (ATmega328P)
button    pin 2 to GND, pinMode(BTN, INPUT_PULLUP)
LED       pin 13 (the on-board LED)
rules     press: on for 10 s, then blink 3 s, then off
          press while on: off
          press while blinking: on for another 10 s
Loading figure…
or ← →
Read the lesson step by step
  1. The job: a stair light

    A stair light on an Arduino Uno R3. Press the button on pin 2 and the LED on pin 13 comes on. After 10 s it blinks for 3 s as a warning, then goes off. A press while it blinks keeps it on.

    board     Arduino Uno R3 (ATmega328P)
    button    pin 2 to GND, pinMode(BTN, INPUT_PULLUP)
    LED       pin 13 (the on-board LED)
    rules     press: on for 10 s, then blink 3 s, then off
              press while on: off
              press while blinking: on for another 10 s
  2. Three named states

    A state is what the device is doing right now. We need three: IDLE, LIGHT and WARN. An enum gives each one a name, and one variable, state, always holds exactly one of them. It starts at IDLE.

    enum State { IDLE, LIGHT, WARN };   // 0, 1, 2
    State state = IDLE;                 // the initial state
    
    IDLE    light off, waiting for a press
    LIGHT   light on, timing 10000 ms
    WARN    light blinking, timing 3000 ms
  3. Two kinds of event

    An event is something that happens. PRESS: pressed() saw a new press on pin 2. TIMEOUT: age(), the time since we entered the state, reached its limit. loop() checks for both on every pass and never waits.

    PRESS     bool press = pressed();   true once per press
              (debounced: 50 ms of quiet, as in "Debouncing a button")
    TIMEOUT   age() >= limit
              age() = millis() - t0, t0 = when we entered the state
    
    no delay(): each pass checks, maybe moves, and returns
  4. switch picks the case

    switch (state) jumps straight to the case for the current state. Each case only checks the events that matter there. break ends the case; without it the code would fall through into the next case.

    line 1    switch (state) {
    IDLE  ->  lines 2-4      LIGHT ->  lines 5-9
    WARN  ->  lines 10-14
    
    break     leaves the switch
              without it, execution falls through into the next case
  5. IDLE + PRESS → LIGHT

    We press. In case IDLE, line 3 sees press and calls go(LIGHT). go() stores the new state and t0 = millis(), the moment we entered it. After the switch, the LED is set from the state: on.

    t = 1000 ms   pressed() returns true
    line 3    if (press) go(LIGHT);
    go()      state = LIGHT;  t0 = millis();
    after     on = (state == LIGHT)  ->  LED on
  6. Waiting without blocking

    In LIGHT nothing happens for a while. Each pass of loop() asks two questions: press? age() >= 10000? No and no, so it moves on at once. age() climbs by itself, because millis() keeps counting.

    every pass, in case LIGHT:
      line 6    press?             no
      line 7    age() >= 10000?    no
      line 9    break;
    
    loop() never stops here, so a press is never missed
  7. LIGHT + TIMEOUT → WARN

    At age() = 10,000 ms, line 7 is true and line 8 calls go(WARN). t0 is reset. Now the LED blinks: (millis() / 250) % 2 flips every 250 ms.

    t = 11000 ms   age() = 10000 ms >= ON_MS
    line 8    go(WARN);
    LED       on while (millis() / 250) % 2 == 0
              250 ms on, 250 ms off: 2 blinks per second
  8. WARN + PRESS → LIGHT

    Someone presses during the warning. Line 11 sends us back to LIGHT, and go() resets t0, so the full 10 s starts again. In LIGHT the same press means off; here it means stay on. The state decides.

    t = 12000 ms   press in WARN
    line 11   if (press) go(LIGHT);
    t0        12000: the 10 s start again
    
    same event, different state, different arrow:
      PRESS in LIGHT -> IDLE      PRESS in WARN -> LIGHT
  9. WARN + TIMEOUT → IDLE

    Left alone, WARN blinks for 3,000 ms. Then line 12 is true and line 13 calls go(IDLE). The LED goes dark. The machine is back where it began, waiting for the next press.

    t = 22000 ms   LIGHT times out -> WARN
    t = 25000 ms   age() = 3000 ms >= WARN_MS
    line 13   go(IDLE);
    LED       off
  10. Five arrows, one table

    The whole design is five arrows: state plus event gives the next state. An event with no arrow is ignored, such as TIMEOUT in IDLE. To add a feature, add a state or an arrow and its case; the rest stays untouched.

    state   event     next     line
    IDLE    PRESS     LIGHT    3
    LIGHT   PRESS     IDLE     6
    LIGHT   TIMEOUT   WARN     8
    WARN    PRESS     LIGHT    11
    WARN    TIMEOUT   IDLE     13
    IDLE    TIMEOUT   (none: ignored)

Quiz Unlocks after the last step.