Most firmware is reactive. It waits for something to happen, such as a button press, a sensor threshold, a timer expiring or a message arriving, and then responds in a way that depends on what it’s currently doing. A finite state machine (FSM) makes “what it’s currently doing” explicit. That replaces a tangle of flags and nested if statements with a small set of named states and clearly defined transitions.
This guide implements the same state machine in embedded C three ways. It then covers the parts that matter on real hardware: events from interrupts, timeouts without blocking delays, and testing.
The example: a tank-filling pump controller
A pump fills a tank when the user presses Start. A float switch reports when the tank is full. If the tank doesn’t fill within 60 seconds, something is wrong (a dry well, a blocked pipe, a failed sensor), so the controller stops the pump and raises an alarm until someone presses Reset.
States: IDLE, FILLING, FULL, FAULT
Events: START, LEVEL_HIGH, LEVEL_LOW, TIMEOUT, RESET
Transitions:
| Current state | Event | Action | Next state |
|---|---|---|---|
| IDLE | START | Pump on, start timer | FILLING |
| FILLING | LEVEL_HIGH | Pump off | FULL |
| FILLING | TIMEOUT | Pump off, alarm on | FAULT |
| FULL | LEVEL_LOW | (none) | IDLE |
| FAULT | RESET | Alarm off | IDLE |
Any event not listed for a state is ignored in that state. For example, pressing Start while already filling does nothing. Writing this table before writing code is the most useful step. It forces you to decide what every event means in every state.
First, the shared types:
#include <stdint.h>
#include <stdbool.h>
typedef enum {
ST_IDLE,
ST_FILLING,
ST_FULL,
ST_FAULT,
ST_COUNT
} state_t;
typedef enum {
EV_START,
EV_LEVEL_HIGH,
EV_LEVEL_LOW,
EV_TIMEOUT,
EV_RESET,
EV_COUNT
} event_t;
/* Hardware hooks, implemented elsewhere */
void pump_on(void);
void pump_off(void);
void alarm_on(void);
void alarm_off(void);
uint32_t millis(void); /* free-running millisecond counter */
Approach 1: switch-case
The most common and most readable approach is a switch on the current state, with event checks inside each case:
static state_t state = ST_IDLE;
static uint32_t fill_start_ms;
void pump_fsm_dispatch(event_t ev)
{
switch (state) {
case ST_IDLE:
if (ev == EV_START) {
pump_on();
fill_start_ms = millis();
state = ST_FILLING;
}
break;
case ST_FILLING:
if (ev == EV_LEVEL_HIGH) {
pump_off();
state = ST_FULL;
} else if (ev == EV_TIMEOUT) {
pump_off();
alarm_on();
state = ST_FAULT;
}
break;
case ST_FULL:
if (ev == EV_LEVEL_LOW) {
state = ST_IDLE;
}
break;
case ST_FAULT:
if (ev == EV_RESET) {
alarm_off();
state = ST_IDLE;
}
break;
default:
/* Corrupted state variable: fail safe */
pump_off();
alarm_on();
state = ST_FAULT;
break;
}
}
The default case matters. If memory corruption or a bug ever leaves state holding an invalid value, the controller drives its outputs to a safe condition instead of doing something undefined.
Adding entry and exit actions
In the version above, the “pump on” and “pump off” actions are repeated at each transition. As a machine grows, it’s cleaner to attach actions to entering and leaving states, and to route every state change through one function:
static void on_exit(state_t s)
{
if (s == ST_FILLING) {
pump_off(); /* pump never stays on after leaving FILLING */
} else if (s == ST_FAULT) {
alarm_off();
}
}
static void on_entry(state_t s)
{
if (s == ST_FILLING) {
pump_on();
fill_start_ms = millis();
} else if (s == ST_FAULT) {
alarm_on();
}
}
static void transition(state_t next)
{
on_exit(state);
state = next;
on_entry(state);
}
The dispatch function then only decides where to go:
case ST_FILLING:
if (ev == EV_LEVEL_HIGH) transition(ST_FULL);
else if (ev == EV_TIMEOUT) transition(ST_FAULT);
break;
The exit action also makes a safety property structural: the pump turns off whenever the machine leaves FILLING, whatever the reason. You no longer depend on remembering pump_off() in every branch.
Approach 2: a transition table
For machines with many states and events, a table can be easier to review against the design:
typedef void (*action_fn)(void);
typedef struct {
action_fn action; /* NULL means: event ignored in this state */
state_t next;
} transition_t;
static void start_fill(void) { pump_on(); fill_start_ms = millis(); }
static void stop_fill(void) { pump_off(); }
static void fault(void) { pump_off(); alarm_on(); }
static void clear_fault(void) { alarm_off(); }
static void no_action(void) { }
static const transition_t table[ST_COUNT][EV_COUNT] = {
[ST_IDLE] = {
[EV_START] = { start_fill, ST_FILLING },
},
[ST_FILLING] = {
[EV_LEVEL_HIGH] = { stop_fill, ST_FULL },
[EV_TIMEOUT] = { fault, ST_FAULT },
},
[ST_FULL] = {
[EV_LEVEL_LOW] = { no_action, ST_IDLE },
},
[ST_FAULT] = {
[EV_RESET] = { clear_fault, ST_IDLE },
},
};
void pump_fsm_dispatch(event_t ev)
{
if ((unsigned)state >= ST_COUNT || (unsigned)ev >= EV_COUNT) {
fault();
state = ST_FAULT;
return;
}
const transition_t *t = &table[state][ev];
if (t->action == NULL) {
return; /* not handled in this state */
}
t->action();
state = t->next;
}
A few details:
- The designated initializers (
[ST_IDLE] = ...) are C99. Entries you don’t list are zero-initialized, so theiractionisNULL. That’s why every real transition needs a non-NULL action, even if it’s justno_action. - The table is
const, so on most microcontrollers it stays in flash and uses no RAM. - Lookup takes constant time regardless of how many states exist.
The downside is that guard conditions, such as “only go to FULL if the level has been high for 200 ms”, don’t fit neatly into a plain table. You end up putting logic inside action functions anyway.
Approach 3: one function per state
A third style stores the current state as a pointer to a handler function. Each state’s handler deals with its own events:
typedef struct pump_fsm pump_fsm_t;
typedef void (*state_handler)(pump_fsm_t *me, event_t ev);
struct pump_fsm {
state_handler state;
uint32_t fill_start_ms;
};
static void st_idle(pump_fsm_t *me, event_t ev);
static void st_filling(pump_fsm_t *me, event_t ev);
static void st_full(pump_fsm_t *me, event_t ev);
static void st_fault(pump_fsm_t *me, event_t ev);
static void st_idle(pump_fsm_t *me, event_t ev)
{
if (ev == EV_START) {
pump_on();
me->fill_start_ms = millis();
me->state = st_filling;
}
}
static void st_filling(pump_fsm_t *me, event_t ev)
{
if (ev == EV_LEVEL_HIGH) {
pump_off();
me->state = st_full;
} else if (ev == EV_TIMEOUT) {
pump_off();
alarm_on();
me->state = st_fault;
}
}
static void st_full(pump_fsm_t *me, event_t ev)
{
if (ev == EV_LEVEL_LOW) {
me->state = st_idle;
}
}
static void st_fault(pump_fsm_t *me, event_t ev)
{
if (ev == EV_RESET) {
alarm_off();
me->state = st_idle;
}
}
void pump_fsm_init(pump_fsm_t *me) { me->state = st_idle; }
void pump_fsm_dispatch(pump_fsm_t *me, event_t ev) { me->state(me, ev); }
Because the state lives in a struct, you can run several independent instances, for example one per pump. This is also the basic idea behind frameworks such as Quantum Leaps’ QP. One caution: a corrupted function pointer jumps to an arbitrary address, so some safety-oriented coding standards prefer an enum with range checking.
Comparing the three approaches
| Switch-case | Transition table | State functions | |
|---|---|---|---|
| Readability for small machines | Best | Good | Good |
| Review against a design table | Fair | Best | Fair |
| Guard conditions and complex logic | Easy | Awkward | Easy |
| Multiple instances | Needs a struct | Needs a struct | Natural |
| Corrupted-state handling | default case |
Range check | Harder |
| RAM use | Minimal | Table in flash | Minimal |
For most projects, start with switch-case plus entry/exit actions. Move to a table when the machine gets large and regular, or to state functions when you need many instances or are heading toward a framework.
Feeding events from interrupts
Events usually start in interrupts: a GPIO edge from the Start button, a UART byte, a timer tick. It’s tempting to call pump_fsm_dispatch() directly from the ISR. Avoid that. The main loop might be in the middle of a transition when the interrupt fires, and the state machine would then run reentrantly on half-updated data.
A simple event queue
The usual solution is for the ISR to post an event to a small queue, which the main loop drains:
#define EVQ_SIZE 16u /* must be a power of two */
static volatile uint8_t evq[EVQ_SIZE];
static volatile uint8_t evq_head; /* written only by the producer (ISR) */
static volatile uint8_t evq_tail; /* written only by the consumer (main) */
/* Called from a single ISR */
bool evq_post(event_t ev)
{
uint8_t next = (uint8_t)((evq_head + 1u) & (EVQ_SIZE - 1u));
if (next == evq_tail) {
return false; /* queue full: event dropped */
}
evq[evq_head] = (uint8_t)ev;
evq_head = next;
return true;
}
/* Called from the main loop */
bool evq_get(event_t *ev)
{
if (evq_tail == evq_head) {
return false; /* empty */
}
*ev = (event_t)evq[evq_tail];
evq_tail = (uint8_t)((evq_tail + 1u) & (EVQ_SIZE - 1u));
return true;
}
This works without disabling interrupts as long as there’s one producer and one consumer on a single-core MCU, and the indices are a size the CPU reads and writes atomically (a byte here). If several ISRs, or both an ISR and the main loop, can post events, protect evq_post() with a short critical section. Count dropped events too, because a full queue usually means the main loop is too slow or something is flooding events. The volatile qualifiers are explained in the volatile keyword in embedded C. Keeping the ISR itself short is covered in how to write an interrupt service routine in C.
Run-to-completion
With a queue, each event is processed fully, including the transition plus exit and entry actions, before the next one starts. This run-to-completion rule is what keeps state machines predictable. It also means actions must be short. A blocking delay inside an action stalls every other event.
Handling timeouts without blocking
The pump’s 60-second limit shouldn’t be a delay(60000). Instead, record a timestamp on entry to FILLING (already done above) and check the elapsed time from the main loop:
#define FILL_TIMEOUT_MS 60000u
bool pump_fsm_fill_timed_out(void)
{
return (state == ST_FILLING) &&
((uint32_t)(millis() - fill_start_ms) >= FILL_TIMEOUT_MS);
}
The unsigned subtraction gives the correct elapsed time even when the 32-bit millisecond counter wraps around (after about 49.7 days), as long as intervals are shorter than the wrap period.
The main loop
Putting it together:
int main(void)
{
hw_init(); /* clocks, GPIO, interrupts, millisecond timer */
for (;;) {
event_t ev;
while (evq_get(&ev)) {
pump_fsm_dispatch(ev);
}
if (pump_fsm_fill_timed_out()) {
pump_fsm_dispatch(EV_TIMEOUT);
}
/* Optionally sleep until the next interrupt (e.g. __WFI() on Cortex-M).
Make sure a periodic timer interrupt wakes the CPU so timeouts
are still checked. */
}
}
The ISRs for the Start button, the float switch and the Reset button each call evq_post() with the right event. Debouncing can happen in the ISR with a timestamp check, or as its own small state machine.
Testing the state machine on a PC
Because the state machine only calls a few hardware hooks (pump_on(), alarm_on(), millis()), you can compile it on a PC with fake versions of those functions and drive it from a unit test:
/* test_pump_fsm.c (host build) */
static bool pump_is_on;
static uint32_t fake_ms;
void pump_on(void) { pump_is_on = true; }
void pump_off(void) { pump_is_on = false; }
void alarm_on(void) { }
void alarm_off(void){ }
uint32_t millis(void) { return fake_ms; }
void test_timeout_stops_pump(void)
{
pump_fsm_dispatch(EV_START);
fake_ms += 60000u;
if (pump_fsm_fill_timed_out()) {
pump_fsm_dispatch(EV_TIMEOUT);
}
TEST_ASSERT_FALSE(pump_is_on);
}
(TEST_ASSERT_FALSE comes from the Unity test framework. Any framework works.) Test every row of your transition table, plus a few events that should be ignored, such as START while FILLING. This catches most logic bugs before they reach hardware.
Common mistakes
- Dispatching from an ISR instead of queuing the event, which leads to reentrancy and races.
- Blocking inside an action (delays, waiting on a flag), which stalls every other event.
- Forgetting the “ignored” cases. Decide explicitly what each event means in each state.
- No safe default for an invalid state value.
- State hidden in flags. If you find yourself adding
bool is_waiting_for_ackbeside the state variable, that flag is probably a missing state. - Not logging transitions. A one-line log or trace of
old → new (event)makes field problems far easier to diagnose. When that isn’t enough, see debugging microcontrollers with JTAG, SWD and GDB.
When to move beyond a flat state machine
Flat state machines get unwieldy when many states share behavior. Suppose every state must respond to EMERGENCY_STOP the same way. Options:
- Hierarchical state machines (statecharts): states nest inside parent states, and an event a child state doesn’t handle passes up to its parent. One
OPERATINGsuperstate can handleEMERGENCY_STOPfor all its substates. - Frameworks: QP/C and QP/C++ from Quantum Leaps implement hierarchical state machines and event-driven “active objects” for microcontrollers, with a graphical modeling tool. They’re available under open-source and commercial licenses.
- Active objects on an RTOS: each state machine runs in its own task with its own event queue. That’s the same run-to-completion idea, scaled up to several independent machines.
Even then, the fundamentals stay the same: explicit states, events through a queue, short actions and a transition table you can review. For more on structuring firmware around these patterns, see the embedded firmware development overview and embedded C programming for microcontrollers.