How do you write a state machine in C?
Short answer: Represent the states with an enum. Either use a switch on the current state inside a function that receives events (clear for small machines), or a table indexed by state and event that gives the next state and an action function (scales well and maps directly to a state diagram). Always handle unexpected events explicitly.
1. Switch-based
typedef enum { ST_IDLE, ST_CONNECTING, ST_CONNECTED } state_t;
typedef enum { EV_START, EV_OK, EV_FAIL, EV_TIMEOUT } event_t;
static state_t state = ST_IDLE;
void fsm_dispatch(event_t ev)
{
switch (state) {
case ST_IDLE:
if (ev == EV_START) { start_link(); state = ST_CONNECTING; }
break;
case ST_CONNECTING:
if (ev == EV_OK) { notify_up(); state = ST_CONNECTED; }
else if (ev == EV_FAIL || ev == EV_TIMEOUT) { log_fail(); state = ST_IDLE; }
break;
case ST_CONNECTED:
if (ev == EV_FAIL) { notify_down(); state = ST_IDLE; }
break;
default:
state = ST_IDLE; /* corrupted state: recover */
break;
}
}
2. Table-driven
typedef struct { bool valid; state_t next; void (*action)(void); } trans_t;
static const trans_t table[3][4] = { /* [state][event] */
[ST_IDLE] = { [EV_START] = { true, ST_CONNECTING, start_link } },
[ST_CONNECTING] = { [EV_OK] = { true, ST_CONNECTED, notify_up },
[EV_FAIL] = { true, ST_IDLE, log_fail },
[EV_TIMEOUT] = { true, ST_IDLE, log_fail } },
[ST_CONNECTED] = { [EV_FAIL] = { true, ST_IDLE, notify_down } },
};
void fsm_dispatch_table(event_t ev)
{
const trans_t *t = &table[state][ev];
if (!t->valid) {
log_unexpected(state, ev); /* unhandled pair: log, ignore or fault */
return;
}
if (t->action) t->action();
state = t->next;
}
Entries not listed are zero-initialised, so valid is false for every unhandled (state, event) pair.
3. State functions: each state is a function returning the next state function; compact, and each state's logic is together.
Good practice
- Keep the table
const(it lives in flash and cannot be corrupted). - Events come from ISRs through a queue; the state machine runs in the main loop or a task, never inside the ISR.
- Use entry/exit actions for things like starting and stopping timers.
- Log state transitions; it makes field debugging much easier.
- For complex behaviour, use hierarchical state machines (UML statecharts; QP/C, or code generation from a diagram).
Embedded examples: protocol parsers (byte-by-byte frame decoding), connection managers, button handling (idle/pressed/long-press), power management, bootloader update flows.