State machine fundamentals
States, events, transitions, actions, Mealy and Moore.
Firmware is mostly state machines
A washing machine is filling, washing, draining or spinning. A BLE connection is advertising, connecting, connected or disconnecting. A protocol parser is waiting for a header, reading a length, reading a payload or checking a CRC. Whenever behaviour depends on what happened before, you have a state machine, whether you wrote it as one or as a tangle of flags. Writing it explicitly makes it readable, testable and complete.
The vocabulary
| Term | Meaning | Washing-machine example |
|---|---|---|
| State | A mode with its own behaviour, where the system waits | FILLING |
| Event | Something that happens | WATER_LEVEL_REACHED, DOOR_OPENED |
| Transition | A change from one state to another in response to an event | FILLING --level reached--> WASHING |
| Guard | A condition that must be true for the transition | [temperature ok] |
| Action | What happens during a transition, or on entering or leaving a state | Close the inlet valve |
A transition is written: SOURCE --event [guard] / action--> TARGET.
Drawing it first
Before coding, draw the states as boxes and transitions as arrows. Then, for every state, ask "what happens if each event arrives here?". This table is where state machines earn their value: it forces you to decide what happens when the door opens during the spin cycle, a question a flag-based design never asks.
| State \ Event | START | LEVEL_OK | TIMER | DOOR_OPEN |
|---|---|---|---|---|
| IDLE | → FILLING / open valve | ignore | ignore | ignore |
| FILLING | ignore | → WASHING / close valve, start motor | → FAULT (filling too long) | → PAUSED / close valve |
| WASHING | ignore | ignore | → DRAINING / stop motor, start pump | → PAUSED / stop motor |
| DRAINING | ignore | ignore | → IDLE / stop pump | ignore (door locked) |
Every cell is a decision. "Ignore" is a decision too, and should be deliberate.
Mealy and Moore
The two classic forms differ in where outputs come from:
| Moore machine | Mealy machine | |
|---|---|---|
| Outputs depend on | The current state only | The current state and the event |
| Actions attached to | States (entry actions) | Transitions |
| Number of states | Often more | Often fewer |
| Output timing | Changes after the state changes | Can respond immediately to an input |
Firmware state machines are usually a mix: entry and exit actions on states (Moore-like), plus actions on specific transitions (Mealy-like). UML statecharts formalise exactly that mix.
A minimal implementation
#include <stdio.h>
typedef enum { ST_IDLE, ST_FILLING, ST_WASHING, ST_DRAINING, ST_PAUSED } state_t;
typedef enum { EV_START, EV_LEVEL_OK, EV_TIMER, EV_DOOR_OPEN, EV_DOOR_CLOSED } event_t;
static const char *const state_name[] = { "IDLE", "FILLING", "WASHING", "DRAINING", "PAUSED" };
static state_t state = ST_IDLE;
static state_t resume_to;
static void dispatch(event_t ev) {
state_t next = state;
switch (state) {
case ST_IDLE: if (ev == EV_START) next = ST_FILLING; break;
case ST_FILLING: if (ev == EV_LEVEL_OK) next = ST_WASHING;
else if (ev == EV_DOOR_OPEN) { resume_to = ST_FILLING; next = ST_PAUSED; } break;
case ST_WASHING: if (ev == EV_TIMER) next = ST_DRAINING;
else if (ev == EV_DOOR_OPEN) { resume_to = ST_WASHING; next = ST_PAUSED; } break;
case ST_DRAINING: if (ev == EV_TIMER) next = ST_IDLE; break;
case ST_PAUSED: if (ev == EV_DOOR_CLOSED) next = resume_to; break;
}
if (next != state) {
printf("%-8s -> %s\n", state_name[state], state_name[next]);
state = next;
}
}
int main(void) {
event_t script[] = { EV_START, EV_LEVEL_OK, EV_DOOR_OPEN, EV_TIMER, EV_DOOR_CLOSED, EV_TIMER, EV_TIMER };
for (unsigned i = 0; i < sizeof script / sizeof script[0]; i++) dispatch(script[i]);
return 0;
}
Notice the EV_TIMER while paused is ignored, exactly as the table says, and resume_to remembers where to go back: a small piece of extended state. When extended state grows large, consider splitting the machine or using hierarchy (see hierarchical state machines).
Signs you need a state machine
- Boolean flags that are only meaningful in certain combinations (
is_connecting && !is_connected && retry_pending). ifchains checking several flags at the top of a function.- Bugs of the form "this works unless X happens while Y".
- Timeouts that must be cancelled depending on what happened.
Replacing five booleans (32 combinations, most of them invalid) with one state variable of six values removes whole classes of bugs.
Rules that keep machines healthy
- One place changes the state. Only the dispatch function assigns the state variable.
- Handle every event in every state, even if the handling is "ignore" or "log as unexpected".
- Events are processed one at a time, to completion. Do not dispatch a new event from inside an action; queue it.
- Log transitions. A trace of
old -> new (event)is the most useful debug output a firmware can have. - Test transitions, not just paths: drive the machine with event sequences and check the resulting states and actions.
Interview question: How do you decide the states of a state machine?
Answer: A state is a distinct mode in which the system waits and reacts to events differently from other modes. List the modes the system can be in where the response to the same event differs, and merge candidates that behave identically. Avoid encoding things that are data (a counter value) as states; keep those as extended state variables with guards. Then build the state-event table and decide every cell, which usually reveals missing states such as a fault or paused state.
Interview question: What problems do state machines solve compared with flag-based code?
Answer: Flag-based logic allows invalid combinations of flags, scatters the rules for each mode across the code and leaves the response to unexpected event orders undefined. A state machine has exactly one current state, makes every transition explicit in one place, forces a decision for each event in each state, and is easy to log, visualise and test, so ordering bugs such as an event arriving during a transition become visible and handled.
Build it: the charger's states
This is step 1 of the module project, the controller of an electric-car charging station. Everything it does depends on what state it is in: a car plugged in but not paid for must never get power. Before any code switches anything, the states and the moves between them have to be exactly right.
Lab: Write the charging station's transition function
The product owner's state diagram, written as a table. Any event not listed for a state is ignored: the station stays where it is.
| State | Event | Next state |
|---|---|---|
ST_IDLE | EV_PLUG (a car is connected) | ST_PLUGGED |
ST_PLUGGED | EV_CARD_OK (payment accepted) | ST_CHARGING |
ST_PLUGGED | EV_UNPLUG | ST_IDLE |
ST_CHARGING | EV_FULL or EV_STOP (the driver pressed stop) | ST_DONE |
ST_CHARGING | EV_UNPLUG (the cable was pulled out while live) | ST_FAULT |
ST_DONE | EV_UNPLUG | ST_IDLE |
ST_FAULT | EV_RESET (a technician cleared it) | ST_IDLE |
any state but ST_FAULT | EV_FAULT (ground fault, overheating) | ST_FAULT |
Write next_state(s, e), which returns the state after event e in state s. It only decides; nothing is switched yet (that is step 2).
A rejected card (EV_CARD_BAD) changes nothing, and neither does a second EV_PLUG. An unknown state or event, which can only come from a bug or corrupted memory, also leads to ST_FAULT: the safe place.
Going deeper
Interview question: How would you design the controller of a pedestrian crossing?
Answer: As a state machine: traffic green, amber, red, walk, flashing don't walk, and back, with the button only latching a request that is served after a minimum green time. Encode the safety rule (never green for cars and pedestrians together) in the structure itself, run it from a fixed-rate tick, and add a fail-safe state (flashing amber) for faults.
Interview question: How would you test a state machine?
Answer: Keep the transition logic pure (next state and actions computed from current state and event) so it runs on a PC. Write tests that put the machine in each state and deliver each event, checking the resulting state and actions, including events that should be ignored, plus sequences reproducing real scenarios and edge cases such as timeouts during transitions. Coverage of every state-event cell, not just happy paths, is the goal.
Interview question: What is extended state, and when should it become a real state instead?
Answer: Extended state is data kept alongside the state variable, such as a retry count or a stored setpoint, used in guards and actions. When behaviour differs substantially depending on that data, so many guards test it and transitions branch on it, it is better modelled as separate states, which makes the behaviour explicit. Numeric data such as counters should stay as extended state with guards.
Explain it: In your own words, explain how a state machine helps with events that arrive at unexpected times.
Answer: In flag-based code, an event arriving in an unusual situation, such as the door opening during the spin cycle, is handled wherever the code happens to check it, often in a way nobody planned. A state machine has a single current state and a definite response to each event in each state, which you can lay out as a table and fill in completely, so every combination gets a deliberate decision: handle it, ignore it or treat it as a fault. Unexpected orderings stop being undefined behaviour and become visible, reviewable and testable.