The machine
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.
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.
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.
The firmware
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.
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.
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.
Running it
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.
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.
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.
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.
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.