C1236 of 55
0 XP
  1. Hook
  2. Play
  3. Predict
  4. Name it
  5. Check
  6. Explain

C12 · Lesson 36 · State machines

Programs that remember where they are

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

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

Predict

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

Name it

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 ⌈log2⁡n⌉ bits (C7). In firmware the enum is usually an int; the count matters for hardware machines and packed storage.

Worked example

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

Show the 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.

Worked example

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

Show the 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.8s
  2. Without a request. Green lasts until there is one.

Answer 2.8 s.

Worked 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?

Show the solution
  1. Size the table. 5×4=20bytes
  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

The crossing spends at least 1000 ms in green, 300 in yellow, 1500 in walk and 1000 in red. With a request always waiting, how long is one full cycle?

Write units the way you normally would: 1.5 ms, 1500 µs and 0.0015 s are the same answer.

Check

How many bits does it take to store one of 5 states?

Check

A machine has 4 states and 2 kinds of event. How many entries does a complete transition table have?

Check

Green must last at least 1000 ms, and the walk button is pressed 400 ms after green began. When does green end?

Write units the way you normally would: 1.5 ms, 1500 µs and 0.0015 s are the same answer.

Check

A button cycles a machine through 3 states (0 → 1 → 2 → 0 ...), starting at 0. After 5 presses, which state is it in?

Check

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

Check

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 on the course's RISC-V board (10 MHz, no floating point). #include "board.h" for the registers; print(x) shows a number. Tab indents; press Esc and then Tab to move on.

Check

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 on the course's board: machine (Pin, PWM, ADC, DAC, UART, I2C, SPI, Timer, WDT) and time. Each call into the hardware takes about 40 µs. Tab indents; press Esc and then Tab to move on.

Check

A table-driven state machine has 6 states and 3 events, 2 byte(s) per entry.

(a)

How big is the table?

(b)

How many transition tests cover every entry?

Check

A crossing runs green 10 s, yellow 3 s, all-red 2 s, then walk 12 s, and back to green.

(a)

How long is a full cycle?

Write units the way you normally would: 1.5 s and 1500 ms are the same answer.

(b)

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

Explain why

Why do state machines suit embedded programs so well?

Practice

Keep practicing

10 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.