Event-driven state machines
From polling to events, queues and run-to-completion.
From polling to events
A first state machine is often written as a polling loop: every pass, look at the current state, read inputs, decide whether to change state.
for (;;) {
switch (state) {
case WAIT_BUTTON: if (button_pressed()) state = DEBOUNCE; break;
case DEBOUNCE: if (millis() - t0 > 20) state = ...; break;
}
}
This works, but it burns CPU checking things that have not changed, its response time depends on how long the rest of the loop takes, and inputs are read at arbitrary moments, so a short pulse can be missed between polls.
An event-driven state machine inverts this: the machine does nothing until an event is delivered to it. Interrupts, timers and other modules produce events; a dispatcher feeds them to the machine one at a time. Between events, the CPU can sleep.
The ingredients
- Events as small structs: a type, and optionally data.
- An event queue per state machine. Producers (ISRs, other machines, timers) post into it.
- A dispatcher that takes one event at a time and calls the machine's handler.
- Run-to-completion: the handler for one event finishes completely before the next event is taken.
#include <stdio.h>
#include <stdint.h>
typedef enum { EV_BUTTON, EV_TIMEOUT, EV_DATA } ev_type_t;
typedef struct { ev_type_t type; uint16_t data; } event_t;
/* A small ring-buffer event queue. In a real system, ISRs post with interrupts briefly masked. */
#define QLEN 8
static event_t q[QLEN];
static unsigned head, tail;
static int post(event_t e) { if (head - tail == QLEN) return -1; q[head++ % QLEN] = e; return 0; }
static int get(event_t *e) { if (head == tail) return 0; *e = q[tail++ % QLEN]; return 1; }
typedef enum { IDLE, MEASURING } state_t;
static state_t state = IDLE;
static uint32_t total, count;
static void handle(const event_t *e) {
switch (state) {
case IDLE:
if (e->type == EV_BUTTON) { total = count = 0; state = MEASURING; printf("start measuring\n"); }
break;
case MEASURING:
if (e->type == EV_DATA) { total += e->data; count++; }
if (e->type == EV_TIMEOUT) { printf("done: %u samples, average %u\n", count, count ? total / count : 0); state = IDLE; }
break;
}
}
int main(void) {
/* Events produced by interrupts and timers, in arrival order. */
post((event_t){ EV_DATA, 7 }); /* ignored: not measuring yet */
post((event_t){ EV_BUTTON, 0 });
post((event_t){ EV_DATA, 40 });
post((event_t){ EV_DATA, 44 });
post((event_t){ EV_TIMEOUT, 0 });
event_t e;
while (get(&e)) handle(&e); /* the dispatcher; sleeps when the queue is empty */
return 0;
}
Run-to-completion
Run-to-completion (RTC) means a machine never sees a new event while it is still handling the previous one. Within one handler, the state is consistent: no other event can change it halfway. This removes the need for locks inside a machine, which is the main reason event-driven designs are easier to get right than threads sharing variables.
RTC does not mean the handler cannot be preempted. An interrupt or a higher-priority task can run in the middle; it just cannot deliver an event into this machine except by posting to its queue, which is processed later.
Consequences:
- Handlers must be short and never block. A handler that waits 500 ms for a flash erase stalls every event behind it. Start the operation, return, and handle a
FLASH_DONEevent later. - An action that needs to trigger another transition posts an event rather than calling the handler recursively.
Timers as events
Timeouts are the most common events. Rather than checking millis() in states, arm a timer that posts an event when it expires:
case CONNECTING:
if (e->type == EV_ENTRY) timer_arm(&conn_timer, 5000, EV_CONNECT_TIMEOUT);
if (e->type == EV_CONNECTED) { timer_disarm(&conn_timer); transition(CONNECTED); }
if (e->type == EV_CONNECT_TIMEOUT) transition(BACKOFF);
break;
Disarm timers on exit from the state that armed them, or a stale timeout will arrive in a later state. Tagging timeout events with a generation number and ignoring old ones is a robust alternative.
With an RTOS
The natural mapping is one task per state machine (an "active object"): the task blocks on its queue, and each received event is dispatched to the machine. ISRs post with xQueueSendFromISR. Machines talk to each other only by posting events, never by calling each other's functions or sharing variables.
void comms_task(void *arg) {
event_t e;
comms_init();
for (;;) {
xQueueReceive(comms_queue, &e, portMAX_DELAY);
comms_dispatch(&e);
}
}
Several machines can also share one task with a priority queue, which is how frameworks such as QP's cooperative kernel work with very little RAM.
Designing the event queue
- Size: the worst-case burst between dispatches. Measure the high-water mark.
- Overflow policy: decide per event type. Losing a "button pressed" is bad; losing one of a stream of sensor samples may be acceptable. Count drops either way.
- Event data: keep events small and copy them. For large payloads, post a pointer to a pool block whose ownership passes with the event.
- Priorities: some designs use two queues (urgent and normal) or post urgent events to the front.
Pitfall: Calling the dispatcher from inside an ISR to "save latency" breaks run-to-completion: the ISR can run in the middle of a handler and change the state underneath it. ISRs only post.
Interview question: How do you handle a long operation, such as erasing flash, inside an event-driven state machine?
Answer: Never block in the handler. Split it: in the action, start the operation (or ask a worker to do it) and transition to a waiting state such as ERASING, then return. When the hardware completes, its interrupt or the worker posts an ERASE_DONE event (and a timer posts a timeout event if it never completes), and the machine continues from the waiting state. Other events arriving meanwhile are handled or deferred according to the ERASING state's rules.
Interview question: What is an active object?
Answer: A design pattern combining a state machine, a private event queue and its own thread of execution (a task, or a slot in a cooperative scheduler). It encapsulates its data, communicates with others only by posting asynchronous events, and processes its events one at a time with run-to-completion semantics. Because no data is shared, it avoids most locking, and it maps naturally onto an RTOS task blocking on a queue.
Build it: an event queue between the interrupts and the state machine
This is step 3 of the module project. Events come from interrupts: the card reader's UART, the plug-detect pin, the ground-fault detector. An interrupt handler must be short, so it does not run the state machine itself; it posts an event to a queue, and the main loop takes events out and dispatches them one at a time, in order.
Lab: A ring-buffer event queue the interrupts post to
Write a queue of up to QUEUE_SIZE (8) events, kept in a ring buffer with a head (where the next event is written) and a tail (where the next one is read).
event_post(e)is called from interrupt handlers. It adds the event and returns true, or, when the queue is full, drops it, counts it and returns false. It must never block, and never overwrite an event that has not been read.event_get(e)is called from the main loop. It takes the oldest event and returns true, or returns false when the queue is empty.events_dropped()returns how many events were dropped since start-up. A non-zero count in the field log tells the team the main loop is too slow.charger_run()takes every queued event, in order, appliesnext_state()from step 1 to the charger's state, and returns how many it handled.
One exception: a fault must never be lost. When the queue is full and EV_FAULT is posted, it still has to get through. Do it by putting the charger straight into ST_FAULT in event_post (the state variable is shared with the main loop, so it is volatile), and still count the dropped event.
The checks play interrupts landing in bursts while the main loop is busy.
Going deeper
Interview question: How would you make a smart lock handle keypad, phone and door-sensor events arriving in any order?
Answer: Each source posts events to a queue, and one state machine consumes them one at a time, so the order is well defined and nothing is processed half-way. Each state explicitly handles or ignores every event, which you can test as a table. Timeouts are events too, from a timer service, and the queue is sized for the worst burst.
Interview question: How should timeouts be implemented in an event-driven state machine?
Answer: Arm a software timer on entry to the state that needs it, which posts a timeout event to the machine's queue when it expires, and disarm it on exit. Tagging the timeout event with a generation number guards against a stale timeout that was already queued arriving in a later state. The machine never polls time in its states.
Interview question: What happens if an event queue fills up, and how do you design for it?
Answer: New events are lost or the producer must block, and an interrupt cannot block. Size queues for the worst-case burst measured on the target, decide per event type whether dropping is acceptable (a repeated sensor sample) or not (a button press), count drops for diagnostics, and for critical events use a separate high-priority queue or a flag that coalesces repeats.
Explain it: In your own words, explain why an interrupt should post an event rather than call the state machine directly.
Answer: A state machine handles one event at a time to completion, so within a handler its state is always consistent. If an interrupt called the dispatch function directly, it could run in the middle of another event's handling and change the state or data underneath it, breaking that guarantee and causing rare, hard-to-reproduce bugs. Posting the event to the machine's queue lets the interrupt finish quickly and the machine process it later, after the current event is fully handled.