Embedded HandbookApps
All sections › XV. C in depth
STM32F103, STM32F407, STM32G031 · level intermediate · 29 min read
Open in the interactive handbook

125а. State machines in firmware: switch, a transition table, hierarchy, an event queue from interrupts and timeouts

Almost any firmware is a state machine, even if its author never said the word. A button is released, bouncing, pressed, held. A frame receiver waits for a sync byte, a length, data, a checksum. A device is off, idle, measuring, calibrating, in a fault. When this is written as a scatter of flags is_pressed, waiting_len, calib_running, a year later nobody can say which combinations are possible and which are a bug. When it is written as a state machine, all possible positions are listed, and every transition is visible in one place.

The section covers a machine on switch, a transition table on an array of structures with function pointers (a continuation of section 125), entry and exit actions, a hierarchical machine where a parent handles an event for all nested states, an event queue written by an interrupt, the atomicity of that queue on Cortex-M, timeouts as ordinary events, the same machine in a FreeRTOS task, typical mistakes and testing the machine on the computer. Three running examples: a button with debouncing and a long press, parsing a frame byte by byte and the modes of a device.

Basis: alg.c with all the machines of the section built with gcc 12.2.0 on the computer (stm-sys:1, flags -Wall -Wextra -Werror) and run by host.c: the queue for overflow and for the index wrapping past 255, a comparison of switch and the table on all 35 "state × event" pairs, the order of entry and exit actions, a stale timeout, a main loop of 5001 ticks and the same scenario in an RTOS task with a stub queue, the button on a bouncing signal, parsing a stream of 41 bytes. The button and the frame parser are recomputed independently in Python on the same input data. The same alg.c built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) at -O2 for Cortex-M4F and Cortex-M0 — function sizes, stack frames and the sizes of the tables in flash. There are no cycles here: nothing was measured on silicon.

Terms used in the documentation

Original Meaning
transition table (state × event) transition table: a row "state, event → action, new state"
entry action, exit action entry action and exit action: run on every entry to a state and exit from it
guard condition guard: the transition fires only if it is true
hierarchical state machine (HSM) hierarchical machine: a state may contain nested ones
superstate, substate parent and nested state
least common ancestor (LCA) the nearest common ancestor of two states: exits go up to it, entries go down from it
run-to-completion (RTC) the next event is taken only when the previous one has been handled completely
event dispatch handing an event to the machine: find the transition and perform it
self-transition transition to itself: exit from and re-entry to the same state

In plain words. A state machine is a device with a mode knob. At any moment the knob is in exactly one position — that is the state. Events come from outside: a button was pressed, a byte arrived, time ran out. On each event the device looks at its table: "I am in such-and-such position, such-and-such arrived — so do this and turn the knob there". If there is no such row in the table, the event is simply not needed in this position.


125а.1 State, event, transition

Three words on which everything else rests.

A state is what the device "remembers" about the past and what determines its reaction to the future. There is a finite number of states, and at any moment exactly one is active. Off, idle, measuring — these are states. A sensor reading is not a state but data: it can take thousands of values, and which events the device is ready to accept does not depend on it.

An event is something that happened outside or inside: a button was pressed, a byte arrived, a timer expired, a fault was detected. An event is instantaneous and carries a short detail: which byte, which button.

A transition is a rule "in state S on event E perform action A and go to state T". A guard may be attached to a transition: "START leads to measuring only if the device is calibrated".

In this section events are small numbers, and the detail is one byte:

enum {
    EV_NONE, EV_POWER, EV_START, EV_DONE, EV_CALIB, EV_TIMEOUT, EV_FAULT, EV_RESET, EV_COUNT
};

typedef struct {
    uint8_t sig; /* что случилось */
    uint8_t arg; /* подробность: байт, номер кнопки, поколение таймера */
} event_t;

Two bytes per event — enough that it can be copied in one operation and that a queue of dozens of events fits in a couple of dozen bytes of RAM.

The device modes on which the whole section is built are five working states and one parent:

Hierarchical state machine of the device modes: OFF on the left, FAULT on the right, between them a large parent state ON with IDLE, MEASURE and CALIB inside; transitions are labelled with events: POWER, START with the guard "calibrated", DONE, TIMEOUT, CALIB; POWER and FAULT are handled by the parent ON for all nested states; RESET leads from FAULT to OFF; MEASURE and CALIB arm a 500 and 3000 ms timer on entry

The full transition table of this device is 35 "state × event" pairs, and the state changes in only 14 of them:

from \ event POWER START DONE CALIB TIMEOUT FAULT RESET
OFF IDLE · · · · · ·
IDLE OFF MEASURE · CALIB · FAULT ·
MEASURE OFF · IDLE · IDLE FAULT ·
CALIB OFF · IDLE · FAULT FAULT ·
FAULT · · · · · · OFF

A dot means the event is not needed in this state, and the state stays the same. It is worth drawing such a table before the first line of code: the empty cells immediately raise questions that otherwise a user in the field answers. What happens if POWER is pressed in a fault? Here — nothing: only RESET leads out of a fault.


125а.2 A machine on switch

The most direct notation is a switch on the current state with an event check inside. The function is pure: state and event in, the new state out. We will add actions later; for now it is important to see the transitions themselves:

state_t mode_switch(state_t s, uint8_t sig)
{
    switch (s) {
    case ST_OFF:
        return sig == EV_POWER ? ST_IDLE : ST_OFF;
    case ST_IDLE:
        if (sig == EV_START)
            return ST_MEASURE;
        if (sig == EV_CALIB)
            return ST_CALIB;
        break;
    case ST_MEASURE:
        if (sig == EV_DONE || sig == EV_TIMEOUT)
            return ST_IDLE;
        break;
    case ST_CALIB:
        if (sig == EV_DONE)
            return ST_IDLE;
        if (sig == EV_TIMEOUT)
            return ST_FAULT;
        break;
    case ST_FAULT:
        return sig == EV_RESET ? ST_OFF : ST_FAULT;
    default:
        return ST_FAULT; /* сюда не попадаем; попали — это сбой */
    }
    if (sig == EV_POWER) /* общее для IDLE, MEASURE и CALIB */
        return ST_OFF;
    if (sig == EV_FAULT)
        return ST_FAULT;
    return s;
}

Note the tail after the switch: POWER and FAULT are handled the same way in three states, and instead of three copies there is one check "for everyone who did break". This is already the germ of the hierarchy of 125а.5 — only written implicitly, by the order of lines.

The advantages of switch: it reads top to bottom, the compiler builds a jump table or a chain of comparisons by itself, and the function is small — 92 bytes of code for both Cortex-M4F and Cortex-M0, with no stack. The drawback: when there are ten states and fifteen events, the function stretches over screens, and reactions common to a group of states spread out as copies.

The default branch is needed even if all values of the enumeration are listed: the state variable lives in RAM, and a power glitch, an overrun of a neighbouring array or a cosmic particle can write anything there. A device in an unknown state must go to a safe one rather than silently carry on.


125а.3 A transition table: an array of structures and function pointers

The second notation is data instead of code. Each transition is a row of the table: from where, on which event, with which guard, with which action, to where. The guard and the action are function pointers, exactly like the command handlers in section 125:

typedef struct {
    bool (*guard)(const device_t *d);
    void (*action)(device_t *d);
    uint8_t state;
    uint8_t sig;
    uint8_t next;
} trans_t;

The device table is ten rows, constant, that is, it lives in flash:

static const trans_t TRANS[] = {
    /* условие      действие        откуда      событие     куда */
    {NULL,          NULL,           ST_OFF,     EV_POWER,   ST_IDLE},
    {NULL,          NULL,           ST_ON,      EV_POWER,   ST_OFF},
    {NULL,          NULL,           ST_ON,      EV_FAULT,   ST_FAULT},
    {is_calibrated, NULL,           ST_IDLE,    EV_START,   ST_MEASURE},
    {NULL,          NULL,           ST_IDLE,    EV_CALIB,   ST_CALIB},
    {NULL,          act_store,      ST_MEASURE, EV_DONE,    ST_IDLE},
    {NULL,          act_timeout,    ST_MEASURE, EV_TIMEOUT, ST_IDLE},
    {NULL,          act_calibrated, ST_CALIB,   EV_DONE,    ST_IDLE},
    {NULL,          NULL,           ST_CALIB,   EV_TIMEOUT, ST_FAULT},
    {NULL,          NULL,           ST_FAULT,   EV_RESET,   ST_OFF},
};

A person reads the table without reading code: the row ST_IDLE, EV_START → ST_MEASURE with the guard is_calibrated — and everything is clear. Adding a transition means adding a row. It can also be generated from a diagram or, conversely, a diagram can be drawn from the table.

The order of the fields is not accidental. On Cortex-M a pointer takes 4 bytes, and the uint8_t fields after two pointers give a 12-byte row: a table of 10 transitions is 120 bytes of flash, as arm-none-eabi-nm showed for both M4F and M0. If the three bytes are put in front of the pointers, the compiler inserts padding (section 126), and the row becomes 16 bytes. On the computer the same row weighs 24 bytes — pointers there are 8 bytes each, so a sizeof printed on the PC says nothing about the firmware.

The price of the table is the dispatch function that walks it: it is shared by any machines, but larger than the switch of one machine (comparison in 125а.11).


125а.4 Entry and exit actions

Many states have things to do on entering them, whichever side they are entered from, and on leaving, wherever they lead. Entered measuring — turn on the ADC and arm a timer. Left — stop the timer. If this is written in the transition actions, stopping the timer has to be repeated in every transition out of measuring: on DONE, on TIMEOUT, on POWER, on FAULT. Forget it in one — and the timer ticks in someone else's state.

The solution is a state description with two pointers, for entry and for exit:

typedef struct {
    uint8_t parent;
    void (*entry)(device_t *d);
    void (*exit)(device_t *d);
} state_desc_t;

For measuring and calibration this is a pair of functions that arm and stop the state timer:

static void measure_entry(device_t *d) { trace(d, 1, ST_MEASURE); timer_arm(d, MEASURE_MS); }
static void measure_exit(device_t *d) { trace(d, 2, ST_MEASURE); timer_stop(d); }
static void calib_entry(device_t *d) { trace(d, 1, ST_CALIB); timer_arm(d, CALIB_MS); }
static void calib_exit(device_t *d) { trace(d, 2, ST_CALIB); timer_stop(d); }

trace writes an entry "entry/exit/action, state" into an array — for checking on the computer (125а.10). The order in a transition is fixed: first the exits from the old states, then the transition action, then the entries into the new ones. A run of calibration finished by DONE gave exactly that:

trace_calib:      +CALIB
trace_calib_done: -CALIB *CALIB +IDLE

Plus is an entry, minus is an exit, the asterisk is the transition action act_calibrated. The exit from CALIB stopped the timer before the action declared the device calibrated, and the entry to IDLE came last.


125а.5 A hierarchical machine: nested states

In the table of 125а.1 IDLE, MEASURE and CALIB react identically to POWER and FAULT. In a flat machine that is three pairs of rows. In a hierarchical one these three states are nested in the parent ON, and the POWER and FAULT rows are written once — in the parent. The dispatch rule: look for a transition in the current state; not found — in its parent; not found — in the parent's parent; reached the root — the event is not needed.

for (uint8_t s = d->state; s != ST_NONE; s = STATES[s].parent) {
    for (unsigned i = 0; i < NTRANS; i++) {
        const trans_t *t = &TRANS[i];
        if (t->state != s || t->sig != e.sig)
            continue;
        if (t->guard && !t->guard(d))
            continue;
        hsm_transit(d, t);
        d->depth--;
        return;
    }
}
d->ignored++; /* событие не нужно ни состоянию, ни его родителям */

The state descriptions define the tree with the parent field:

static const state_desc_t STATES[ST_COUNT] = {
    [ST_OFF]     = {ST_NONE, off_entry, NULL},
    [ST_ON]      = {ST_NONE, on_entry, on_exit},
    [ST_IDLE]    = {ST_ON, idle_entry, NULL},
    [ST_MEASURE] = {ST_ON, measure_entry, measure_exit},
    [ST_CALIB]   = {ST_ON, calib_entry, calib_exit},
    [ST_FAULT]   = {ST_NONE, fault_entry, NULL},
};

The subtlest part is which entries and exits to perform in a transition between states of different depth. The answer is given via the nearest common ancestor: exit from the current state upwards to the common ancestor, not including it, perform the action, enter from the common ancestor downwards to the target:

static void hsm_transit(device_t *d, const trans_t *t)
{
    uint8_t path[HSM_MAX_DEPTH], n = 0;
    uint8_t lca = lca_of(d->state, t->next);
    for (uint8_t s = d->state; s != lca; s = STATES[s].parent)
        if (STATES[s].exit)
            STATES[s].exit(d);
    if (t->action)
        t->action(d);
    for (uint8_t s = t->next; s != lca && n < HSM_MAX_DEPTH; s = STATES[s].parent)
        path[n++] = s;
    while (n) {
        uint8_t s = path[--n];
        if (STATES[s].entry)
            STATES[s].entry(d);
    }
    d->state = t->next;
}

The downward path is collected from the target to the ancestor, and the entries are performed in reverse order — first the outer, then the nested one. For a self-transition the common ancestor is the parent, so the state exits and enters again: that is how a state timer is restarted with one row of the table.

The run shows how this works on the device:

trace_power:  +ON +IDLE
trace_start2: +MEASURE
trace_fault:  -MEASURE -ON +FAULT
trace_reset:  +OFF

On POWER from OFF the common ancestor is the root: entered ON first, then IDLE. From IDLE to MEASURE the common ancestor is ON: there is neither an exit from ON nor an entry to it, only the entry to MEASURE. The fault arrived in MEASURE, but MEASURE has no FAULT row — it was found in the parent ON. The exits are still done properly: first from MEASURE (the timer is stopped), then from ON, then the entry to FAULT.

A guard works the same way: START in an uncalibrated device did not pass the guard is_calibrated, the parent has no START row, the event is counted as unneeded, the device stays in IDLE (ignored=1 in the run). POWER in a fault did nothing either: FAULT is not nested in ON.

Hierarchy is not always needed. If the machine fits on a screen and there are no common reactions, a flat one is simpler. It pays off when a group of states has a common exit (fault, power-off, link loss) or a common entry-exit (sensor power, backlight): the parent keeps them in one place.


125а.6 An event queue: the interrupt only puts the event

Where should the machine be called? The temptation is right in the interrupt handler: a byte arrived — hsm_dispatch from USART1_IRQHandler. This must not be done, for three reasons. A handler must be short: the machine's actions write to flash, send over UART, compute — all this delays other interrupts. The machine can be poked by two interrupts of different priorities, and one preempts the other in the middle of a transition — the state ends up half written. And the machine no longer "runs to completion": an event arriving in the middle of a transition bursts into it.

The right way is to split: the interrupt puts an event into a queue and leaves, the main loop (or an RTOS task) takes events one at a time and hands them to the machine. The queue is a ring buffer of 8 events, the indices are free-running uint8_t, the place in the array is the index masked:

#define EVQ_SIZE 8u /* степень двойки */

typedef struct {
    event_t buf[EVQ_SIZE];
    volatile uint8_t head;    /* пишет только производитель */
    volatile uint8_t tail;    /* пишет только потребитель */
    volatile uint8_t dropped; /* сколько событий не влезло */
} evq_t;

The difference head - tail in uint8_t is the number of events in the queue, and it is correct even after the indices wrap past 255, because 256 is divisible by 8. The run: 300 events put and taken one at a time went through without loss, and head afterwards equals 52 — the eight events of the first experiment plus 300, that is, 308 modulo 256: the index honestly went past zero.

bool evq_put(evq_t *q, event_t e)
{
    uint8_t h = q->head;
    if ((uint8_t)(h - q->tail) >= EVQ_SIZE) {
        q->dropped++;
        return false;
    }
    q->buf[h & (EVQ_SIZE - 1u)] = e;
    COMPILER_BARRIER(); /* сначала данные, потом индекс */
    q->head = (uint8_t)(h + 1u);
    return true;
}

Overflow is not a crash but an event to be counted: a burst of 12 events into a queue of 8 put 8, lost 4 and honestly increased dropped to 4; the eight events taken came out in the order in which they arrived. The loss counter is reported in diagnostics: if it grows, the queue is too small or the main loop does not keep up.

The main loop is three lines per tick: the events scheduled by interrupts are already in the queue, the timers are checked, the queue is drained to the bottom:

void dev_tick(device_t *d, uint32_t now)
{
    d->now = now;
    if (d->timer_on && (int32_t)(now - d->deadline) >= 0) {
        d->timer_on = false;
        evq_put_locked(d->q, (event_t){EV_TIMEOUT, d->tgen});
    }
}

The run-to-completion rule holds by itself: until hsm_dispatch has returned, the next event is not taken from the queue. And if an action needs to produce a new event — say, to start measuring right after calibration — it puts it into the same queue rather than calling hsm_dispatch from inside itself. The dispatch nesting counter in the main loop run never rose above 1.


125а.7 Atomicity on Cortex-M

Why does the queue above work without disabling interrupts? Because each index has one writer: head is written only by the interrupt, tail only by the main loop. A byte store on Cortex-M is one strb instruction, it cannot be interrupted in the middle; the reading side sees either the old value or the new one. The order matters: first put the event in the array, then move the index. volatile on the indices keeps the compiler from holding them in a register, and COMPILER_BARRIER() — an empty assembly insert with a memory "clobber" — keeps it from moving the array store after the index store. On a single-core Cortex-M0/M3/M4 the processor itself does not reorder ordinary stores to memory so that its own interrupt would see them in a different order — the barrier is for the compiler. On multi-core parts (the dual-core H7) hardware __DMB() barriers are needed as well.

Everything changes when there are two writers: a button interrupt and a UART interrupt with different priorities, or an interrupt and the main loop itself. Both read head, both write into the same slot, one index is lost. Then the store is protected from preemption: save PRIMASK, disable interrupts, put, restore PRIMASK as it was:

static inline uint32_t irq_save(void)
{
#if defined(__arm__)
    uint32_t m;
    __asm__ __volatile__("mrs %0, primask\n\tcpsid i" : "=r"(m) : : "memory");
    return m;
#else
    return 0;
#endif
}

It must be saved rather than simply re-enabled at the end because the function may be called with interrupts already disabled — and a cpsie i at the end would enable them too early. The price is a few instructions with interrupts disabled: on Cortex-M4F evq_put_locked takes 74 bytes against 60 for evq_put. On M3/M4 there is also a way without disabling — the exclusive ldrex/strex (section 124), but Cortex-M0 does not have them, while every core has PRIMASK.

One surprise of the run: on Cortex-M0 both evq_put and evq_get call memcpy — to copy the two-byte event_t structure, whose alignment the compiler is not sure of on M0 (an unaligned access on M0 gives a HardFault). Because of this the stack frame of evq_put on M0 is 24 bytes, while on M4F it is 8. In an interrupt handler such a call costs extra cycles; if that matters, the event is stored as two byte writes or packed into a uint16_t.


125а.8 Timeouts as events

A timeout is not a special mechanism but an event just like a press. A state arms its timer on entry and stops it on exit (125а.4); the main loop compares the time with the deadline once per tick and, if it has passed, puts EV_TIMEOUT into the queue. The comparison is via a signed difference: (int32_t)(now - deadline) >= 0 is correct even after the millisecond counter wraps past 0xFFFFFFFF, roughly once every 49.7 days (details in 76г.4).

The main loop was run for 5001 ticks with events "from interrupts" on a schedule. The transitions and the time they happened:

loop: 10:IDLE 20:CALIB 3020:FAULT 3100:OFF 3110:IDLE 3120:CALIB 3500:IDLE 3600:MEASURE 4100:IDLE 4200:MEASURE 4300:IDLE

Calibration was started at the 20th millisecond, and DONE did not come — 3000 ms later, at the 3020th, the timeout fired, and the device went into a fault. After RESET and a repeated calibration finished in time, the measurement at 3600 ended by timeout at 4100, and the measurement at 4200 by DONE at 4300. The result of the run: one stored measurement, one measurement timeout, one fault, zero losses in the queue.

A stale timeout. The subtle point is a timeout lying in the queue when its state has already changed. The scenario: a measurement is running, the queue already holds DONE and a new START, and at that moment the timer of the old measurement expires — an EV_TIMEOUT lands in the queue. The drain: DONE → IDLE, START → a new measurement, and after it the old TIMEOUT throws the new measurement out as soon as it has begun. The protection is a timer generation: each timer_arm increments tgen, the timeout event carries the generation in arg, and dispatch discards a timeout of a foreign generation:

if (e.sig == EV_TIMEOUT && d->check_gen && e.arg != d->tgen) {
    d->ignored++; /* таймаут прошлого состояния */
    d->depth--;
    return;
}

A run of both variants on this scenario:

generation check final state measurement timeouts discarded
no IDLE 1 0
yes MEASURE 0 1

Without the check the new measurement is killed by someone else's timeout; with the check it goes on. In the field such a bug is seen as "sometimes a measurement is cut short immediately" — and reproducing it on the bench is almost impossible because it requires a coincidence to the millisecond.


125а.9 A button: debouncing and a long press

A mechanical contact "bounces" for several milliseconds on pressing and releasing — it closes and opens. Naive edge counting sees dozens of presses instead of one. The button machine samples the pin once per 1 ms and accepts a level only if it has held for 20 ms in a row. Five states: released, waiting for press confirmation, pressed, held, waiting for release confirmation:

enum { BTN_EV_NONE, BTN_EV_PRESS, BTN_EV_CLICK, BTN_EV_LONG };
enum { BTN_UP, BTN_DOWN_WAIT, BTN_DOWN, BTN_LONG, BTN_UP_WAIT };
#define BTN_DEBOUNCE_MS 20u
#define BTN_LONG_MS 800u

The transition from waiting to "pressed" happens only after 20 ms of a stable level; any dip in the level returns to "released":

case BTN_DOWN_WAIT:
    if (!level) {
        b->st = BTN_UP; /* дребезг или помеха */
        return BTN_EV_NONE;
    }
    if (++b->t < BTN_DEBOUNCE_MS)
        return BTN_EV_NONE;
    b->st = BTN_DOWN;
    b->hold = 0;
    b->was_long = false;
    return BTN_EV_PRESS;

Holding 800 ms after confirmation gives LONG; releasing after LONG no longer gives a click — the was_long flag remembers what kind of press it was:

case BTN_UP_WAIT:
    if (level) {
        b->st = b->was_long ? BTN_LONG : BTN_DOWN; /* дребезг отпускания */
        return BTN_EV_NONE;
    }
    if (++b->t < BTN_DEBOUNCE_MS)
        return BTN_EV_NONE;
    b->st = BTN_UP;
    return b->was_long ? BTN_EV_NONE : BTN_EV_CLICK;

The signal for the run is 2848 ms: a short 150 ms press with 5–6 ms of bounce at the edges, an 8 ms glitch, a long 1200 ms press, a double click of 60 ms each with an 80 ms pause. The result:

what count
rising edges in the signal 18
confirmed presses 4
clicks 3
long presses 1

Eighteen edges are what an edge interrupt handler without debouncing would have seen. The machine saw four presses: the short one, the long one and two in the double click; the 8 ms glitch is filtered out because it is shorter than 20 ms. The long press is reported at the 1646th millisecond — still during the hold, exactly 800 ms after confirmation, not on release; so the user sees a reaction without letting go of the button. The same signal was fed through an independent Python implementation — the events and times agreed.

The button machine is 146 bytes of code on M4F and 152 on M0, no stack frame, 6 bytes of RAM per button. It does not need an edge interrupt: sampling once per 1 ms from the tick is cheaper and does not wake the processor on every bounce.


125а.10 Parsing a protocol byte by byte

A frame receiver is a classic state machine: bytes arrive one at a time from the UART interrupt, and after each one it must remember which field of the frame we are at. The frame: sync byte 0x55, length (0–16), command, data, CRC-8 over the length, command and data (polynomial 0x07). The states mirror the fields:

enum { P_SYNC, P_LEN, P_CMD, P_DATA, P_CRC };

Each state accepts its own byte and decides where to go next. The length check comes immediately, before the data: a length over 16 will not fit in the buffer, and a frame with it is discarded rather than written past the end of the array:

case P_LEN:
    if (b > PROTO_MAX) {
        p->bad_len++;
        p->st = (b == PROTO_SYNC) ? P_LEN : P_SYNC;
        return 0;
    }
    p->len = b;
    p->crc = crc8(0, b);
    p->st = P_CMD;
    return 0;

The machine's second event is a pause. If a frame was cut off (interference, a cable unplugged), the machine gets stuck in the middle of a frame and takes the start of the next one as data. A gap between bytes longer than 5 ms becomes a "timeout" event, which returns the machine to searching for the sync byte:

void proto_timeout(proto_t *p)
{
    if (p->st != P_SYNC) {
        p->timeouts++;
        p->st = P_SYNC;
    }
}

The stream for the run is 41 bytes: three bytes of garbage, two good frames (the second has a 0x55 byte among its data), a frame with a corrupted CRC, a sync byte with length 40, a good frame without data, a cut-off frame, a 20 ms pause and one more good frame. The result:

what count
frames accepted 4
discarded by CRC 1
discarded by length 1
reset by pause 1

Commands 0x21, 0x22, 0x24 and 0x26 were accepted — all the good frames. The 0x55 byte inside the data of the second frame did not derail parsing: in the P_DATA state it is just data. The cut-off frame would have eaten the sync byte of the last frame as its own data byte — the 20 ms pause saved it: the timeout returned the machine to searching for the sync byte before that byte arrived. The same stream was parsed by an independent Python implementation — the same result.

Where should proto_byte be called? By the rule of 125а.6 — not in the interrupt but from the main loop: the UART interrupt puts the byte into the queue (the event's detail is the byte itself in arg) or into the receive ring buffer from the UART section, and the main loop feeds the bytes to the machine. The parsing function is 238 bytes of code on M4F, 240 on M0.

This format has an irremovable weakness: after a corrupted frame the machine searches for 0x55 and may take a byte from the middle of the garbage for the start of a frame. The CRC will almost certainly discard such a false frame, but once in 256 a random CRC will match. Where that is unacceptable, frames with byte stuffing (COBS, SLIP) are used, in which a sync byte inside the data is impossible.


125а.11 A state machine in an RTOS task

Under FreeRTOS the machine lives in its own task, and the event queue is an ordinary FreeRTOS queue: the interrupt puts an event with xQueueSendFromISR, the task sleeps in xQueueReceive. The state timer need not be checked every tick: the task waits for an event exactly until the deadline of the nearest timeout, and if nothing arrived in that time — that is the timeout:

void mode_task_step(mode_task_ctx_t *c)
{
    device_t *d = &c->dev;
    event_t e;
    TickType_t wait = portMAX_DELAY;
    if (d->timer_on) {
        int32_t left = (int32_t)(d->deadline - xTaskGetTickCount());
        wait = left > 0 ? (TickType_t)left : 0;
    }
    if (xQueueReceive(c->q, &e, wait) == pdTRUE) {
        d->now = xTaskGetTickCount();
        hsm_dispatch(d, e);
    } else if (d->timer_on) {
        d->now = xTaskGetTickCount();
        d->timer_on = false;
        hsm_dispatch(d, (event_t){EV_TIMEOUT, d->tgen});
    }
}

The task itself is an endless loop around this step; the step is moved into a function so it can be checked on the computer. The same scenario as in 125а.8 was run through mode_task_step with stubs of xQueueReceive and xTaskGetTickCount that advance model time:

rtos: 10:IDLE 20:CALIB 3020:FAULT 3100:OFF 3110:IDLE 3120:CALIB 3500:IDLE 3600:MEASURE 4100:IDLE 4200:MEASURE 4300:IDLE

The transitions and times agreed with the main loop to the millisecond, and the task woke 11 times in 4300 ms — nine events and two timeouts. The main loop of 125а.8 checked the timer on each of thousands of ticks over the same time. This is the gain of a task: the processor sleeps while the machine has nothing to do.

The machine's now field is time in RTOS ticks; if a tick is not 1 ms, the deadlines MEASURE_MS and CALIB_MS are converted via pdMS_TO_TICKS. And one rule stays the same: a state machine does not wait. No vTaskDelay inside an action — a delay is expressed as a state timeout, otherwise the task stops accepting events while it sleeps in the action.

Where the tables and functions of the machine go in memory — a comparison of the two notations on Cortex-M:

Function M4 code bytes M4 frame M0 code bytes M0 frame
mode_switch 92 0 92 0
hsm_dispatch 628 56 684 56
button_step 146 0 152 0
proto_byte 238 0 240 12
evq_put 60 8 64 24
evq_put_locked 74 8 72 24

hsm_dispatch with the hierarchy, entries, exits and the common ancestor search (the compiler inlined everything) is 628 bytes, and the TRANS and STATES tables are another 120 + 72 bytes of flash. A flat switch of one machine is 92 bytes. But hsm_dispatch is written once for the whole firmware and serves any number of machines, while each new machine is only its tables and small entry and exit functions (18–36 bytes each on M4F). With three or four machines with hierarchy the table is already cheaper.


125а.12 How to test a state machine on the computer

A state machine is an ideal candidate for a unit test on the PC (section 129а): it has no hardware, only an "event" input and a "new state and actions" output. Everything in this section was checked exactly this way, and the techniques are general.

Faking time. The machine does not read SysTick itself — time comes as an argument dev_tick(d, now) or in the now field. The test spins time in a loop and goes through 5000 ms of model time in a fraction of a second.

An action log. Every entry, exit and transition action writes a short record to the trace array. The test compares the log with the expected one: -MEASURE -ON +FAULT — exactly three steps in exactly this order.

Exhaustive pairs. There are few states and events, and all pairs can be enumerated. Here two notations of one machine were compared this way — the switch of 125а.2 and the hierarchical table: on all 35 pairs they gave the same new state. If someone fixes one notation and forgets the other, the test fails.

An independent model. For the button and the frame parser the input data (the signal millisecond by millisecond, the byte stream with pauses) are printed by the bench, and the check in Python recomputes the answer with its own implementation. Agreement of two implementations written differently catches bugs that the author of one implementation does not see.

RTOS stubs. xQueueReceive and xTaskGetTickCount on the computer are a dozen lines: a queue with arrival times and a model clock. The task code does not change — only what is beneath it changes.

Compiler warnings as a test. Building with -Wall -Werror checks by itself that a switch over an enumeration is complete — see "Pitfalls".


125а.13 Where else state machines appear and how they are drawn

A state machine is the common language of firmware: a protocol receiver, a power manager (run — sleep — deep sleep), a connection (search — connect — exchange — loss), a charger (precharge — current — voltage — done), a bootloader (wait — receive — verify — run). For large machines there are code generators from a diagram, and the notation of nested states, entries and exits itself is taken from UML state diagrams. But a generator is not required: a ten-row table written by hand reads no worse than a diagram, and it can go into the documentation as is.

Without an OS a state machine is the heart of the superloop (section 23а): the main loop goes round draining the queues of several machines. With an OS each large machine is in its own task (125а.11), and they communicate by events through queues (sections 27 and 28).


125а.14 Pitfalls

A forgotten state in a switch. A state was added to the enumeration, but no branch was written in the switch. If the switch has no default, gcc -Wall warns (on the bench with a test file):

warning: enumeration value 'A_FAULT' not handled in switch [-Wswitch]

But as soon as there is a default, -Wswitch is silent — -Wswitch-enum is needed, it warns about every unlisted value even with a default. Enable both: default catches garbage in the variable, the warning catches the author's forgetfulness.

The machine is called from an interrupt. Two interrupts of different priorities, and one preempted the other in the middle of a transition: the exit was done, the entry was not. The interrupt only puts an event; dispatch is in one place.

Re-entering dispatch. An action called hsm_dispatch for the next event, and the second transition started in the middle of the first: the entry to the new state ran before the first transition wrote d->state. The action puts the event into the queue; the dispatch nesting counter (depth_max) must stay 1.

Two writers of one queue without protection. The main loop and an interrupt both put events with evq_put without disabling interrupts — the head index is lost. The second writer gets evq_put_locked with PRIMASK.

A stale timeout. A timeout of the previous state arrived in the new one and cut it short. A timer generation in the event: in the run without the check the new measurement was cut short, with the check it continued.

The timer was not stopped. Stopping the timer was missed in one of the four transitions out of a state, and the timer fires in someone else's state. Stopping belongs in the exit action, not in the transition actions.

A delay inside an action. HAL_Delay(500) or vTaskDelay in an action — and the machine is deaf to events for half a second, the queue overflows (dropped grows). A delay is a state with a timeout.

Flags instead of states. Three boolean flags give eight combinations, of which, say, four are valid. The other four will happen one day. An enumeration of states makes invalid combinations inexpressible.

The sizeof of a table computed on the PC. 24 bytes per row on the computer against 12 on Cortex-M: pointers of different width. Sizes for the firmware come only from arm-none-eabi-nm or the .map.


125а.15 Summary

Next: section 126 "Data in memory" — alignment, packing, bit fields and byte order.

Open in the interactive handbook