
Recall first from Embedded limits and compile-time pin configuration
- RTTI, exceptions, and steady-state dynamic allocation are the three features embedded C++ switches off or bans, because they cost flash, add nondeterministic latency, or can fail at run time
- std::array, std::optional, and std::span never allocate from the heap: array and optional store their data inline, span stores only a pointer and a length
- A static_assert inside a class template runs when the template is instantiated, so an invalid pin configuration is a compile error, not a boot-time surprise
From flag soup to explicit states
4 min readIn the last lesson compile-time pin configuration was checked with static_assert. This lesson structures device behavior with state machines: switch and enum, table-driven, polymorphic, and variant-based, plus hierarchical statecharts at a conceptual level.
Consider the simplest real control task on a board: one button, one LED. A short press blinks the LED; holding the button for half a second turns it on until release. Written the direct way, this becomes a pile of booleans: down, was_down, held, led_on, plus a timestamp. Every timer tick and every GPIO edge pokes at several of these flags, and most combinations of the flags are meaningless. What does held == true with down == false mean? The compiler cannot help, because every combination is representable. Bugs in this kind of code are almost always a forgotten combination, not a wrong computation.
A a model with a fixed set of states, a set of input events, and a transition rule that maps (current state, event) to the next state; exactly one state is active at any time removes the illegal combinations by construction. For the button there are three states: Idle (nothing pressed), Pressed (button down, hold threshold not yet reached) and Held (down long enough, LED on). There are three events: Down and Up (debounced edges from the GPIO line) and Tick (a periodic timer event used to measure the hold time). The whole behavior fits in one picture:
The most common implementation is a scoped enum plus a switch. The transition rule becomes a pure function: it reads the current state and the event, and returns the next state, with no side effects at all.
enum class State { Idle, Pressed, Held };
enum class Event { Down, Up, Tick };
State step(State s, Event e) {
switch (s) {
case State::Idle:
if (e == Event::Down) return State::Pressed;
break;
case State::Pressed:
if (e == Event::Up) return State::Idle;
if (e == Event::Tick) return State::Held;
break;
case State::Held:
if (e == Event::Up) return State::Idle;
break;
}
return s; // no rule matched: stay in the current state
}
Two details matter. First, the final return s is a deliberate policy: an event that no rule handles is ignored, and the machine stays put. The alternative, treating it as an error, is also valid, but you must choose one and write it down; an accidental fall-through is how flag-soup bugs come back. Second, because the switch is over an enum class with no default label, GCC's -Wswitch warning (enabled by -Wall) fires if you forget an enumerator. Add a fourth state and every switch that forgot it gets a warning. That is real help, but it is partial: nothing forces you to handle every event inside every case, so a missing rule hides silently in the stay fallback. The other implementations in this lesson attack exactly that weakness.
We compiled this switch machine with -Wall -Wextra (no warnings) and fed it the events Tick, Down, Tick, Up from Idle: the states were 0 1 2 0 (Idle, Pressed, Held, Idle as enum numbers), so the first Tick was ignored. Because step is pure, testing it needs no hardware: call it with every (state, event) pair and compare the result against the diagram. Keep actions (switching the LED) out of step; run them after the transition, based on which state you entered or left. That separation is what makes the same machine runnable on Ubuntu with scripted events and on a Raspberry Pi with real GPIO edges.
The same machine as data, and as objects
4 min readThe switch version mixes two things: the rules of the button, and the C++ control flow that executes them. A an implementation where the transitions live in a data structure (an array of rules or a 2-D table) and one generic engine looks up the next state pulls them apart. The rules become rows:
struct Rule { State from; Event on; State to; };
constexpr Rule rules[] = {
{State::Idle, Event::Down, State::Pressed},
{State::Pressed, Event::Up, State::Idle},
{State::Pressed, Event::Tick, State::Held},
{State::Held, Event::Up, State::Idle},
};
State step(State s, Event e) {
for (const Rule& r : rules)
if (r.from == s && r.on == e) return r.to;
return s;
}
The pay-off is not speed (a linear scan is slower than a switch for tiny machines). The pay-off is that the behavior is now reviewable as a table, can be generated from a specification document, and can be tested exhaustively by iterating over all states and all events. For the button that is 3 times 3, nine pairs: four have rules, five stay. A reviewer can check nine cells in seconds; checking nested switch branches takes much longer. Looping over all nine pairs of the table version, we counted four that change state, matching the four rules.
Because the enum values are small integers, the scan can be replaced by direct indexing, and the whole table can be constexpr. Then the compiler can check the rules, not just store them:
Going deeperCompile-time transition tables with constexpr and static_assert
constexpr State table[3][3] = {
// Down Up Tick
{State::Pressed, State::Idle, State::Idle}, // Idle
{State::Pressed, State::Idle, State::Held}, // Pressed
{State::Held, State::Idle, State::Held}, // Held
};
constexpr State step(State s, Event e) {
return table[static_cast<int>(s)][static_cast<int>(e)];
}
static_assert(step(State::Idle, Event::Down) == State::Pressed);
static_assert(step(State::Pressed, Event::Tick) == State::Held);
static_assert(step(State::Held, Event::Down) == State::Held);
step is a constexpr function reading a constexpr array, so the static_assert lines execute the machine at compile time: a wrong cell fails the build, the same mechanism the previous lesson used for pin configuration. We built it and the three static_assert lines passed. At run time the table sits in read-only data and a transition is one indexed load, with no search and no chain of branches. If both the state and the event are known at compile time, the compiler folds the call to a constant.
One honest caveat: the rows and columns must match the enum order, and nothing checks that ordering for you. Keep the enums and the table in one header, comment the axes as above, and let the static_assert tests pin down the mapping. This is the compile-time style of the earlier constexpr lessons applied to control logic.
The third classic implementation goes the other way: instead of one function that knows all states, each state becomes a class that knows its own reactions. This is the polymorphic State pattern: an abstract base declares one virtual function per event, each concrete state overrides only the events it handles, and the context holds a pointer to the current state object and forwards events to it.
struct StateBase {
virtual ~StateBase() = default;
virtual StateBase* on_down() { return this; }
virtual StateBase* on_up() { return this; }
virtual StateBase* on_tick() { return this; }
};
struct IdleState : StateBase { StateBase* on_down() override; };
struct PressedState : StateBase { StateBase* on_up() override;
StateBase* on_tick() override; };
struct HeldState : StateBase { StateBase* on_up() override; };
static IdleState idle; static PressedState pressed; static HeldState held;
StateBase* IdleState::on_down() { return &pressed; }
We ran it with the missing definitions added (PressedState::on_up and on_tick, HeldState::on_up): Tick in Idle stayed in Idle, then Down and Tick reached the held object and Up returned to idle. The base-class versions of on_down, on_up and on_tick return this, so the stay policy is inherited instead of repeated. Note the static state objects: states carry no per-instance data here, so one shared instance each is enough and the machine allocates nothing, which keeps it inside the no-heap rules from earlier in this module. The costs are the ones you met in the zero-cost abstractions lesson: every event dispatch is an indirect call through a vtable, which the compiler cannot inline across, and each concrete state adds code. In exchange you get a natural home for per-state data members and for virtual entry() and exit() hooks. The pattern earns its keep when states have rich, differing behavior; for the three-state button it is machinery you do not need.
States and events as types: variant and visit
4 min readA a type-safe union (C++17, header <variant>) that holds exactly one value from a fixed list of alternative types and always knows which alternative is active lets you drop the enums entirely. Each state is a struct, each event is a struct, and the machine's current state is one variant value:
#include <variant>
struct Idle {};
struct Pressed {};
struct Held {};
using State = std::variant<Idle, Pressed, Held>;
struct Down {};
struct Up {};
struct Tick {};
using Event = std::variant<Down, Up, Tick>;
Dispatch is std::visit: it inspects which alternatives are active and calls your visitor with them. Passing two variants visits the pair, which is exactly the (state, event) lookup the table did, but expressed in types. The common idiom builds one visitor out of several lambdas:
Going deeperstd::visit dispatch, exhaustiveness, and what it costs
template <class... Ts> struct Overloaded : Ts... { using Ts::operator()...; };
template <class... Ts> Overloaded(Ts...) -> Overloaded<Ts...>;
State step(const State& s, const Event& e) {
return std::visit(Overloaded{
[](Idle, Down) -> State { return Pressed{}; },
[](Pressed, Up) -> State { return Idle{}; },
[](Pressed, Tick) -> State { return Held{}; },
[](Held, Up) -> State { return Idle{}; },
[](auto cur, auto) -> State { return cur; } // everything else: stay
}, s, e);
}
Overloaded inherits all the lambdas' call operators into one object; the trailing generic lambda is the stay rule for every pair without a specific handler. The explicit -> State on each lambda is needed because the lambdas return different alternative types and must agree on one return type.
We ran this visitor with Down, Tick, Up from Idle: index() was 1, 2, 0 (Pressed, Held, Idle). The safety win is exhaustiveness. The visitor must be callable for every combination of alternatives. Delete the generic fallback and add a fourth state to the variant, and every std::visit site that cannot handle the new state fails to compile, with an error naming the missing combination. We tried it without the fallback: GCC 13 stopped with no matching function for call to __invoke(... const Idle&, const Up&), which names the first unhandled pair, though the message is long and templated. The switch version could only warn about missing states and said nothing about missing events; here the type system enumerates the whole state-times-event space for you.
Types also carry data. Make the timer event struct Tick { int elapsed_ms; }; and the hold threshold becomes a guard inside one lambda, with no shared timestamp variable:
[](Pressed, Tick t) -> State {
return t.elapsed_ms >= 500 ? State{Held{}} : State{Pressed{}};
}
A state can carry data too (a press counter inside Pressed, for example), so per-state variables live in the state instead of beside it.
Cost: a variant is sized for its largest alternative plus a small index, stored inline with no heap. In libstdc++, std::visit compiles to a lookup in a table of function pointers indexed by the active alternatives, then one indirect call: comparable to the polymorphic pattern's vtable call, without requiring inheritance. No exceptions are needed on this path, and nothing allocates, so the style fits the no-heap, exceptions-off builds this module targets.
This is exactly the machine you will build in the practice lab: Idle, Pressed, Held as types, events dispatched with std::visit, and the LED driven by entry and exit actions. Keep step pure and run actions outside it: compare the old and new state (the member function index() reports which alternative is active) and switch the LED only when the state actually changed. On Ubuntu you feed a scripted event sequence, so no board is needed. On a Raspberry Pi the events come from the epoll loop you built earlier in this module: the GPIO edge file descriptors deliver Down and Up, a timerfd delivers Tick, and clock_gettime with CLOCK_MONOTONIC measures the hold duration that the guard checks.
A state machine assumes each event is processed fully (transition plus actions) before the next event begins. Never call step again from inside an action: a nested dispatch can observe a half-updated machine. If an action produces a new event, put it in a queue and let the main loop deliver it after the current event finishes. The later lesson on active objects builds exactly that queue.
Hierarchical machines, and choosing an implementation
4 min readLook again at the button rules: Up returns to Idle from both Pressed and Held. Two states, two copies, no problem. Now imagine ten substates of "button is down" (debouncing, pressed, held, repeating, chording): the flat machine needs ten copies of the Up rule, and every new substate must remember to add one. That duplication is the scaling limit of flat machines, and it is a maintenance bug factory: the copies drift apart.
A a state machine whose states can contain substates; an event not handled by the active substate is offered to its parent, and so on up the hierarchy (HSM) fixes this. Put Pressed and Held inside a superstate Active, and handle Up once, at Active. The active configuration is now a path, Active/Held, not a single cell.
HSMs come from statecharts, introduced by David Harel in his 1987 paper "Statecharts: A Visual Formalism for Complex Systems", developed while he consulted on an avionics project where flat state diagrams had grown unmanageable. Statecharts add three ideas you should know at a conceptual level:
- Entry and exit actions: code attached to a state that runs whenever the state is entered or left, regardless of which transition caused it. Turning the LED on belongs to the entry action of
Held, not to every transition that happens to reachHeld. - Guards: a boolean condition on a transition, written like
Tick [elapsed_ms >= 500]. The transition fires only if the event matches and the guard is true; otherwise the event stays unhandled or takes another rule. - Hierarchy with bubbling: the active substate gets the first chance at an event; if it has no matching transition, the parent is tried, up to the root.
Offer the event: the active substate checks its own transitions first; if none matches, the event bubbles to the parent.
Check the guard: a matching transition fires only if its guard evaluates to true.
Run exit actions: leave the source state, running exit actions upward until the common ancestor of source and target (the ancestor itself is not exited).
Run entry actions: enter states downward from the common ancestor to the target, running each entry action on the way in.
Settle: the target substate is now active, and the next event starts again at step 1.
For a transition from Pressed to Held, the common ancestor is Active: Pressed exits, Held enters, and Active is neither exited nor re-entered, so its entry action does not run again. That boundary rule is the detail interviews probe and hand-rolled hierarchies get wrong. You can encode a hierarchy in any of this lesson's implementations (a parent pointer in the table, a base-class chain in the polymorphic version), and header-only C++ libraries such as Boost.SML implement statecharts directly; reach for one when the nesting gets deep rather than inventing the semantics yourself.
So which implementation fits an embedded control task? For a handful of states and events, enum plus switch is the smallest and clearest thing that works. When the rules should be reviewed, generated, or checked as data, use a table, and make it constexpr so static_assert tests the rules at compile time. When states have rich per-state behavior and natural entry/exit hooks, the polymorphic pattern fits, with static state objects to stay heap-free and an indirect call per event as the price. When you want event payloads, per-state data, and a compiler that enumerates every state/event combination, use std::variant with std::visit. And when transitions start repeating across groups of states, add hierarchy on top of whichever base you chose.
All four implementations still hard-wire what happens on a transition: the LED call sits inside the machine, and the machine knows its drivers. The next lesson, "Observer and dependency injection", answers how the machine announces state changes without knowing who listens, and how to inject the button and LED drivers so the same machine runs against real GPIO or a test double.
Key takeaways
- A finite state machine keeps exactly one active state, so illegal flag combinations become unrepresentable
- A constexpr transition table can be tested with static_assert, and a transition with compile-time-known inputs folds to a constant
- std::visit forces every state/event combination to be handled; adding a variant alternative breaks non-exhaustive visitors at compile time
- Hierarchical state machines share transitions in a parent state and run exit and entry actions when a transition crosses state boundaries
Reflect
- Explain to a colleague, in two sentences: implement a button state machine with enum and switch, and with a constexpr transition table checked by static_assert
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageepoll(7): the epoll interface
- Man pagetimerfd_create(2): timers that notify via file descriptors
- Man pageclock_gettime(2): retrieve the time of a specified clock
Official documentation first. Links checked when the lesson was published.