Table-driven state machine
Look up a transition in a table, run its action and return the next state. A medium embedded C problem (State machines), run and graded in the browser.
medium · State machines · fsm · tables · function-pointers
A transition table keeps a state machine's behaviour in data. Find the first row whose state matches the current state (or is ANY_STATE) and whose event matches the event. Call its action if it has one, and return its next state.
If no row matches, the event is ignored: call nothing and return the current state. Rows are checked in order, so an earlier row overrides a later ANY_STATE row.
Starter code
uint8_t fsm_dispatch(const transition_t *table, size_t n, uint8_t state, uint8_t event) {
for (size_t i = 0; i < n; i++)
if (table[i].state == state && table[i].event == event)
return table[i].next;
return state;
}Example tests
Transitions with actions
step(IDLE, START);
step(RUNNING, FINISH);Expected output:
beep 1
beep 2An event with no row is ignored
step(IDLE, FINISH);Expected output:
0Learn it first
- State machine patterns in C · Switch, transition tables and state-function pointers compared.
More State machines problems
- Traffic light with a fault mode · Write the transition function for a light that cycles, flashes on a fault and resets.
- Keypad code lock · Implement a door lock that takes a 4-digit code, re-locks, and locks out after three failures.
- Garage door controller · Write the transition function of a garage door, including the obstacle safety reversal.
- Click, double-click and long press · Turn a sampled button into click, double-click and long-press events with a state machine.
- Fix: the door opens by itself · A door controller skips its unlocking state.
- Washing machine: the cycle and the door · Run a wash cycle as a state machine that pauses safely when the door opens.