---
title: State machines
heading: Programs that remember where they are
eyebrow: C12 · Lesson 36 · State machines
xp: 40
---

::: hook
A traffic light, a vending machine, a protocol parser and a washing machine all behave differently depending on what has already happened. Writing that as tangled `if`s and flags goes wrong quickly. A **state machine** names each situation the device can be in, a **state**, and lists, for each state, which events move it to which other state. C7 built them in hardware; in firmware the same idea becomes an enum, a variable holding the current state, and a `switch`. It's the most useful single pattern in embedded programming, because it keeps the program responsive: it never waits inside a state, it checks and moves on.
:::

::: play
- A pedestrian crossing: green until someone presses the walk button (P4, pressed at 1.5 s), then yellow, then red with the walk light, then red alone, then green again.
- Each state's code checks its condition (time in the state, a request) and picks the next state. Nothing waits: the loop goes round thousands of times a second.
- Follow the lanes: green (P2) holds until 1.5 s, yellow (P1) for 300 ms, red (P0) with walk (P3) for a second, red alone for 500 ms, then green.
:::
:::

```sim board
lang: c
attach: led P0 | red
attach: led P1 | yellow
attach: led P2 | green
attach: led P3 | white
attach: button P4 | press 1.5..1.6 s
scope: P2, P1, P0, P3, P4
run: 4 s
show: debug
code:
#include "board.h"

enum state { GREEN, YELLOW, WALK, RED };
#define RED_LED    (1 << 0)
#define YELLOW_LED (1 << 1)
#define GREEN_LED  (1 << 2)
#define WALK_LED   (1 << 3)

uint32_t now_ms(void) { return SYS_CYCLES / 10000; }

void lights(uint32_t on) {
    GPIO_CLR = RED_LED | YELLOW_LED | GREEN_LED | WALK_LED;
    GPIO_SET = on;
}

int main(void) {
    GPIO_DIR = RED_LED | YELLOW_LED | GREEN_LED | WALK_LED;
    GPIO_PULLUP = 1 << 4;
    enum state s = GREEN;
    uint32_t entered = now_ms();
    int request = 0;
    lights(GREEN_LED);
    while (1) {
        if (!((GPIO_IN >> 4) & 1)) request = 1;     // someone pressed walk
        uint32_t t = now_ms() - entered;            // time in this state
        enum state next = s;
        switch (s) {
            case GREEN:  if (t >= 1000 && request) next = YELLOW; break;
            case YELLOW: if (t >= 300) next = WALK; break;
            case WALK:   if (t >= 1000) { request = 0; next = RED; } break;
            case RED:    if (t >= 500) next = GREEN; break;
        }
        if (next != s) {                            // entering a new state
            s = next;
            entered = now_ms();
            lights(s == GREEN ? GREEN_LED : s == YELLOW ? YELLOW_LED : s == WALK ? RED_LED | WALK_LED : RED_LED);
        }
    }
}
```

::: predict
## The walk button is pressed 0.4 s after the light turns green. When does the light turn yellow?

- [ ] Immediately, at 0.4 s
- [x] At 1.0 s, when green's minimum time is up
- [ ] At 1.4 s
- [ ] Never, because the press came too early

::: reveal
At 1.0 s. The press sets `request`, and the request is remembered; GREEN moves on only when both its time (1 s) is up and a request is waiting. That's the difference between an event and a state: the press lasts a moment, but the machine records it so it can act on it later.
:::
:::

::: nameit
## The parts

- **States:** the situations, as an `enum` (GREEN, YELLOW, WALK, RED).
- **The current state:** one variable.
- **Transitions:** for each state, the conditions (events, timers, inputs) that move to another state.
- **Entry actions:** what happens on entering a state (here, setting the lights, and noting the time).

The loop never waits inside a state: each pass checks the current state's conditions and returns, so it can watch inputs, other machines and the clock at the same time.

## Writing them

The `switch` form above is the most common. A **table** form lists each (state, event) pair's next state and action in an array, which keeps the structure in one place and suits machines with many states. Drawing the machine first, as circles and arrows, catches missing transitions before they're bugs: every state should say what happens for every event, even if the answer is "nothing".

## Encoding

n states need $\lceil \log_2 n \rceil$ bits (C7). In firmware the enum is usually an `int`; the count matters for hardware machines and packed storage.
:::

::: example
## A button selects among off, slow blink and fast blink, in turn. Draw the machine.

::: solution
1. **List the states.** OFF, SLOW and FAST.
2. **Add the transitions.** A (debounced) press moves OFF → SLOW → FAST → OFF; nothing else changes the state.
3. **Add the timed actions.** In SLOW and FAST, a timer inside the state toggles the LED every 500 ms or 100 ms.

**Answer:** 3 states and 3 transitions, plus a timed action in two of them.
:::
:::

::: example
## How long is the crossing's cycle when someone is waiting at the start of green?

::: solution
1. **Add the phases.** Green 1 s, yellow 0.3 s, walk 1 s and red 0.5 s:
   $$1 + 0.3 + 1 + 0.5 = 2.8\ \text{s}$$
2. **Without a request.** Green lasts until there is one.

**Answer:** 2.8 s.
:::
:::

::: example
## A table-driven state machine has 5 states and 4 events, with one byte per next-state entry. How much memory does the table take, and what does a lookup cost?

::: solution
1. **Size the table.**
   $$5 \times 4 = 20\ \text{bytes}$$
2. **Cost of a lookup.** One multiply-and-add for the index and one load: a few cycles, the same for every transition.
3. **Growing it.** Adding a state adds a row of 4 bytes, without touching any code.

**Answer:** 20 bytes, and a few cycles per lookup.
:::
:::

::: check
given: g = 800 | 1000 | 2000; y = 300 | 500; w = 1000 | 1500; r = 500 | 1000
answer: g + y + w + r
unit: ms
tolerance: 0

## The crossing spends at least {g} ms in green, {y} in yellow, {w} in walk and {r} in red. With a request always waiting, how long is one full cycle?

::: right
Right. {answer} ms.
:::

::: misses
- [any] Not yet. Add the four states' times.
:::
:::

::: check
given: n = 3 | 5 | 9 | 17
answer: ceil(log(n)/log(2))
tolerance: 0

## How many bits does it take to store one of {n} states?

::: right
Right. $\lceil\log_2 \given{n}\rceil$ = {answer}.
:::

::: misses
- [any] Not yet. The smallest b with $2^b \ge n$.
:::
:::

::: check
given: s = 3 | 4 | 6; e = 2 | 3 | 4
answer: s*e
tolerance: 0

## A machine has {s} states and {e} kinds of event. How many entries does a complete transition table have?

::: right
Right. {answer}: one for every (state, event) pair, even the ones that do nothing.
:::

::: misses
- [s + e] Each state needs an answer for each event.
- [any] Not yet. States times events.
:::
:::

::: check
given: t0 = 200 | 400 | 700; g = 1000 | 1500
answer: (t0 + g + abs(t0 - g))/2
unit: ms
tolerance: 0

## Green must last at least {g} ms, and the walk button is pressed {t0} ms after green began. When does green end?

::: right
Right. {answer} ms: whichever comes later, the request or the minimum time.
:::

::: misses
- [t0] The minimum green time still has to pass.
- [any] Not yet. Both conditions must hold.
:::
:::

::: check
given: p = 4 | 5 | 7 | 8; k = 3
answer: p - k*floor(p/k)
tolerance: 0

## A button cycles a machine through {k} states (0 → 1 → 2 → 0 ...), starting at 0. After {p} presses, which state is it in?

::: right
Right. State {answer}.
:::

::: misses
- [p] It wraps around after state {k} − 1.
- [any] Not yet. Presses modulo {k}.
:::
:::

::: check
kind: choice

## Why does each state in the play check a condition and move on, instead of calling a delay for its time?

- [ ] Delays are slower to compile
- [x] So the loop keeps checking inputs (the button) while it waits
- [ ] Because switch statements can't contain function calls
- [ ] To use less memory

::: misses
- [1] Compile time has nothing to do with it.
- [3] They can.
- [4] Memory isn't the issue; responsiveness is.
:::
:::

::: check
kind: c
attach: led P0; button P4 | press 0.1..0.12 s, 0.7..0.72 s, 0.8..0.82 s; button P5 | press 0.3..0.32 s, 0.5..0.52 s, 0.9..0.92 s
run: 1.1
expect: edges(P0) = 4; first(P0) = 0.1 s ± 1%; level(P0) = 0

## A turnstile: a coin (button P4) unlocks it; a push (button P5) locks it again. A push while locked or a coin while unlocked changes nothing. Show "unlocked" on the LED at P0. (Both buttons go to ground; there's no bounce.)

```c starter
#include "board.h"

int main(void) {
    GPIO_DIR = 1 << 0;
    GPIO_PULLUP = (1 << 4) | (1 << 5);
    while (1) {
        if (!((GPIO_IN >> 4) & 1)) GPIO_TOGGLE = 1;
    }
}
```

```c solution
#include "board.h"

enum state { LOCKED, UNLOCKED };

int main(void) {
    GPIO_DIR = 1 << 0;
    GPIO_PULLUP = (1 << 4) | (1 << 5);
    enum state s = LOCKED;
    while (1) {
        int coin = !((GPIO_IN >> 4) & 1);
        int push = !((GPIO_IN >> 5) & 1);
        if (s == LOCKED && coin) { s = UNLOCKED; GPIO_SET = 1; }
        else if (s == UNLOCKED && push) { s = LOCKED; GPIO_CLR = 1; }
    }
}
```

::: right
Right. Two states, two transitions; the events that don't apply in a state are simply ignored.
:::
:::

::: check
kind: micropython
attach: led P0; button P4 | press 0.5..0.55 s, 1.5..1.55 s
run: 2.6
expect: period(P0) = 200 ms ± 3%

## The button on P4 steps through three modes: off, slow blink (500 ms on, 500 off), fast blink (100 ms on, 100 off), then back to off. It starts off. Write it as a state machine.

```micropython starter
from machine import Pin
import time

led = Pin(0, Pin.OUT)
button = Pin(4, Pin.IN, Pin.PULL_UP)
while True:
    led.toggle()
    time.sleep_ms(500)
```

```micropython solution
from machine import Pin
import time

led = Pin(0, Pin.OUT)
button = Pin(4, Pin.IN, Pin.PULL_UP)
OFF, SLOW, FAST = 0, 1, 2
HALF = {SLOW: 500, FAST: 100}
state = OFF
last = 1
toggled = time.ticks_ms()
while True:
    now = button.value()
    if last == 1 and now == 0:
        state = (state + 1) % 3
        led.off()
        toggled = time.ticks_ms()
    last = now
    if state != OFF and time.ticks_diff(time.ticks_ms(), toggled) >= HALF[state]:
        led.toggle()
        toggled = time.ticks_ms()
    time.sleep_ms(5)
```

::: right
Right. After the second press it's in FAST, blinking with a 200 ms period.
:::
:::

::: check
kind: parts
given: s = 4 | 6 | 12; e = 3 | 5; b = 1 | 2

## A table-driven state machine has {s} states and {e} events, {b} byte(s) per entry.

::: part
answer: s*e*b
unit: bytes
tolerance: 0

### How big is the table?

::: misses
- [any] States × events × bytes.
:::
:::

::: part
answer: s*e
tolerance: 0

### How many transition tests cover every entry?

::: misses
- [any] One per entry.
:::
:::
:::

::: check
kind: parts
given: g = 10 | 20; y = 3 | 4; w = 7 | 12; r = 1 | 2

## A crossing runs green {g} s, yellow {y} s, all-red {r} s, then walk {w} s, and back to green.

::: part
answer: g + y + w + r
unit: s
tolerance: 0.5%

### How long is a full cycle?

::: misses
- [any] Add the phases.
:::
:::

::: part
answer: g + y + r
unit: s
tolerance: 0.5%

### If a pedestrian presses just as green starts, how long until walk begins (green runs its full time)?

::: misses
- [any] Green, yellow and all-red come first.
:::
:::
:::

::: explain
## Why do state machines suit embedded programs so well?

::: model
An embedded program usually has to watch several things at once (buttons, timers, a serial line) and its correct response depends on what has already happened. A state machine stores the past in one variable and spells out, for each state, exactly which events matter and where they lead, so every case is visible and testable, and impossible combinations of flags can't arise. Because no state waits inside a loop or a delay, the main loop returns quickly and can run several machines side by side, each responding promptly, which is what a cooperative scheduler (next lesson) is built from.
:::
:::

::: practice

::: check
given: g = 1200 | 2000 | 3000 | 5000 | 8000; y = 400; w = 2000; r = 600 | 1000
answer: g + y + w + r
unit: ms
tolerance: 0

## Cycle time: green {g}, yellow {y}, walk {w}, red {r} ms?

::: misses
- [any] Add them.
:::
:::

::: check
given: n = 3 | 5 | 6 | 10 | 12 | 20 | 33 | 100
answer: ceil(log(n)/log(2))
tolerance: 0

## Bits for {n} states?

::: misses
- [any] $\lceil\log_2 n\rceil$.
:::
:::

::: check
given: s = 5 | 8; e = 3 | 6
answer: s*e
tolerance: 0

## Table entries for {s} states and {e} events?

::: misses
- [any] s × e.
:::
:::
:::
