D2D13PRESSPRESSTIMEOUTPRESSTIMEOUTMCUATmega328Pstate-age()-IDLE1switch (state) {2case IDLE:3 if (press) go(LIGHT);4 break;5case LIGHT:6 if (press) go(IDLE);7 else if (age() >= ON_MS)8 go(WARN);9 break;10case WARN:11 if (press) go(LIGHT);12 else if (age() >= WARN_MS)13 go(IDLE);14 break;15}LIGHTWARNpresstime
Back: the button on pin 2, the chip with state and age(), the LED on pin 13Front: the switch (state) card and the state diagram lying on the tableTokens: press and time events hop into the chip; the puck marks the current stateA stair light on an Arduino Uno R3: a button on pin 2 and the LED on pin 13. The firmware is a state machine with three states (IDLE, LIGHT, WARN) and two events (PRESS, TIMEOUT). loop() never waits: on every pass the switch picks the case for the current state, which checks its events and may call go() to move along one of the five arrows. Long waits are sped up.

The machine

  1. 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.

The firmware

Running it

What happens

// step 1/10 · job
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

The card shows only the switch. The whole sketch also declares the enum, go(), age() and a debounced pressed() (the "Debouncing a button" lesson, 50 ms), and sets the LED after the switch. Press checks come before timeouts, so a press always wins in the same pass. 10 s, 3 s and 250 ms are design choices for this example, not standards. The figure speeds up the long waits.