ProjekinAja. Embedded Systems Stage 3 · Firmware Lesson 3.7
● Stage 3 · Lesson 3.7

State Machines and Event-Driven Firmware

The superloop that works on a demo becomes the superloop that blocks on a demo. Events and states scale; delays do not.

⏱ ~26 min read ⚠ The event nobody handled 🔧 Beacon's FSM, every cell

🎯 By the end you'll understand

Why a superloop with delays in it is a scheduling decision disguised as convenience, and the exact point at which it stops working. What an explicit finite state machine actually consists of — states, events, transitions, actions, and the entry and exit work that is easy to leave implicit and expensive to get wrong. How to build the states × events table and why the interesting cells are always the ones you would rather not think about: a button pressed while the sensor is converting, motion detected in the middle of an advertising burst, a report timer expiring while the previous report is still going out. You will implement Beacon's canonical machine — BOOT → SELF_TEST → SLEEP ⇄ WAKE(timer | motion) → SAMPLE → ADVERTISE → SLEEP — with every cell filled, and see what one empty cell costs in battery life.

KEY INSIGHTEvery event happens in every state, whether you planned for it or not

Unit 9 of the pilot came back flat after four days. The firmware was the same as the other twenty-four. The log in the buglog partition ended with SAMPLE → ADVERTISE and then nothing at all — no reset, no panic, no watchdog. The tag had been awake at 40 mA for about twenty-five hours, advertising nothing, waiting for an event that had already arrived while it was not listening.

A state machine is a promise that the device is always in exactly one known condition and that every condition has a way out. Break the promise in one cell of one table and you get a device that is not crashed, not hung in any way a watchdog can see, and not doing anything either: it is waiting, correctly and forever, for a message that was delivered to a state that did not want it. This is the characteristic firmware failure of battery-powered products, and it is not a coding error in the ordinary sense — the code compiles, the logic is right for the case its author imagined, and every unit test passes. The defect is an omission, and omissions are invisible in code review because there is nothing there to look at. The only reliable way to find them is to build the table of every state against every event and be forced to write something in every cell.

🔑 Hold onto this

You do not get to choose which events happen in which states. The user presses the button whenever they like; the accelerometer interrupts whenever the asset moves; the RTC timer expires on its own schedule. Your only choice is whether each combination has a defined response — handle it, defer it, or explicitly discard it — and "explicitly discard" is a real, legitimate, documented answer that is completely different from silence. The cells you leave blank are the ones the field will find.

COMPARISONSuperloop, event-driven, RTOS

Three architectures, and the honest case for each. The mistake is not choosing the simple one; it is failing to notice the day it stopped being sufficient.

Superloop with delaysEvent-driven FSMMultiple RTOS tasks
Shapewhile (1) { read(); delay(1000); send(); }One loop that waits on a queue and dispatches events into a state machineSeveral loops, each blocking on its own thing, scheduled by priority
Good atBeing understood in ten seconds. Blinking things. Bring-up.Devices that must respond to unpredictable events with a bounded response time and a known power stateGenuinely independent activities with different rates — a radio stack, a filesystem, a display
Fails whenAnything must happen during a delay. The first "just add a check inside the loop" is the beginning of an implicit state machine that nobody wrote down.The number of states grows past what one table can express, and sub-states start appearingTasks share data. Then you own priority inversion, stack sizing, and races (3.8).
Power behaviourA delay is awake time unless it is a sleeping delay, and most are notThe loop's idle case is "queue empty" — which is exactly where you call deep sleepDepends entirely on whether every task is blocked; one polling task keeps the chip awake
Debuggability"It stopped" — where?Every transition is a log line: state, event, next state. The trace is the explanation.Interleaved logs from several contexts; correct, and harder to read

Beacon uses the middle column, with a small amount of the right-hand one that it did not choose: the BLE host runs in tasks Espressif wrote, and the accelerometer's ISR posts into a queue (3.4). The application itself is a single task containing a single state machine, and that is a deliberate, defensible simplification for a device whose entire job is a 45-millisecond burst once a minute. Lesson 3.8 makes the argument in full and shows what it would cost to split it up.

🧪 The moment a superloop becomes a state machine

Watch the sequence, because you will live it. Version 1: read the sensor, advertise, delay(60000). Version 2: someone wants the button to work, so the delay becomes a loop that polls the button every 10 ms. Version 3: the button must be debounced, so a counter appears next to the loop. Version 4: motion should shorten the wait, so a flag is checked too — and now the delay loop has three variables in it that describe what the device is currently doing. Those variables are the state; the loop is the transition function; nobody has written either one down, and no table exists to check for gaps. Version 4 is an implicit state machine, and implicit is the whole problem. Making it explicit does not add complexity. It reveals the complexity that was already there.

DEFINITIONWhat an explicit state machine actually is

Five parts, and each one has a rule that experience teaches expensively.

1

States — what the device is doing, not what it knows

A state is a mode of operation with its own set of legal events: SAMPLE, ADVERTISE, SLEEP. "Battery low" is not a state, it is a fact; making facts into states is what causes the combinatorial explosion people blame the technique for. Keep the count small enough to fit on one page — Beacon has six.

2

Events — things that arrive, from outside or from time

An interrupt (motion, button), a timer expiry (the 8.5 ms conversion, the 2 s self-test window), a completion callback (the advertising burst finished), an error return from a driver. Events arrive in a queue and are consumed one at a time, which is what makes the machine's behaviour reproducible.

3

Transitions — (state, event) → next state

This is the table. Its size is states × events, and every cell must contain a decision: change state, stay and do something, or explicitly ignore. There are 6 × 7 = 42 cells in Beacon's machine and roughly a third of them are "ignore, and here is why", which is a perfectly good answer once it is written down.

4

Actions — the work a transition performs

Actions must be short and non-blocking, because the machine cannot process the next event while one is running. "Start the measurement and arm a timer" is an action; "measure and wait 8.5 ms" is a blocked machine (3.6 split the driver in two for precisely this reason).

5

Entry and exit work — the part people leave implicit

Entering SLEEP means clearing the accelerometer's latched interrupt, arming the wake sources, and calling deep sleep. Leaving ADVERTISE means stopping the radio. If that work lives at the call sites instead of at the state boundary, then every new path into the state is a new chance to forget it — and the one that forgets to clear the interrupt latch is the one whose tag never sleeps (3.4).

📖 Deep sleep makes this stranger than a textbook FSM

On the ESP32-C3, entering deep sleep and waking from it is a reset (3.1, 3.3): RAM is gone, app_main runs again from the top, and there is no stack to return to. So Beacon's machine is not one continuous program — it is a program that is re-created about 1,440 times a day and must reconstruct where it was. Two mechanisms do that. esp_sleep_get_wakeup_cause() reports why it woke, which becomes the first event. And variables marked RTC_DATA_ATTR live in RTC memory, which survives deep sleep, holding the sequence number, the moved flag, and the boot count. Everything else starts at zero every minute, and treating that as a feature — no accumulated state, no leaks, no fragmentation — is one of the genuine pleasures of this architecture.

SEE ITFSM simulator: fire events in the awkward order

This is Beacon's machine from the canon. Choose how it handles the four transitions that are easy to leave blank, then inject events by hand — or press the scripted scenario, which fires them in the order a real asset does: a report starts, someone bumps the trolley mid-measurement, the button gets pressed while the radio is still advertising, and the next report timer expires before the last one finished. The current meter and the projected battery life follow the canon's model, so an unhandled event does not print an error. It prints a number.

⚙ Interactive · Beacon's state machine and the cells you would rather skip

Deterministic. Power model from the canon: 8 µA asleep, 40 mA awake, one scheduled report per 60 s, 1000 mAh cell. State durations: WAKE 30 ms, SAMPLE 10 ms (8.5 ms of it the SHT40 conversion), ADVERTISE 5 ms for the three-packet burst, SELF_TEST 2 s at cold boot only.

BOOT SELF_TEST SLEEP WAKE SAMPLE ADVERTISE timer | motion 30 ms 10 ms 5 ms button motion
— cold boot —
State
BOOT
Average current
—
Projected life
—

Set any one policy to "no transition defined" and run the scripted sequence. The log does not show an error; it shows the event arriving and being dropped, and then the machine sitting in a state whose only exit was that event. The average current jumps from tens of microamps to forty milliamps, the projected life falls from years to about a day, and nothing anywhere reports a fault — which is precisely why unit 9 came back flat with a log that ended mid-sentence. Then set them all back and notice how ordinary the correct answers are: latch a flag, defer a press, discard a redundant timer, advertise what you have. None of them is clever. They just had to be written down.

IN PRACTICEThe table you must fill in

Here is Beacon's complete transition table. Six states, seven events, forty-two cells, no blanks. Read the "ignore" cells as carefully as the others — each one is a decision with a reason, which is what separates a documented discard from an omission.

State ↓ / Event →TIMERMOTIONBUTTONSAMPLE_READYSENSOR_ERRADV_DONESELFTEST_DONE
BOOT—
no timer armed yet
ignore
not armed
ignore
too early to mean anything
————
SELF_TESTignoreset moved→ OTA mode (4.9)
the only Rev A opt-in
—log, set fail flag—→ SLEEP
SLEEP→ WAKE(timer)→ WAKE(motion)Rev A: impossible
Rev B: → WAKE(button)
————
WAKEdiscard
already awake
set movedlatch btn_pending————
SAMPLEdiscardset movedlatch btn_pending
act after ADVERTISE
→ ADVERTISEflag stale → ADVERTISE——
ADVERTISEdiscardset moved for the next reportlatch btn_pendingignore
late timer from an aborted sample
ignore→ SLEEP—

Three cells deserve their own paragraph, because they are where the design decisions actually live.

Motion during ADVERTISE. The tempting answer is to abort the burst and start a fresh report that includes the movement. It is wrong for two reasons. The advertising burst is three packets on three channels and takes a handful of milliseconds; aborting it wastes the energy already spent and risks the gateway hearing a partial report. And a device that restarts its report whenever it is moved will, on a trolley being pushed down a corridor, restart continuously and never actually transmit — a livelock built out of entirely reasonable transitions. The correct answer is to set the moved flag in RTC memory so the next report carries it, and to let the current burst finish. Latency to the report is at most one cycle, which R4's two-second budget absorbs easily because a motion event also triggers its own wake.

Button during SAMPLE. Acting immediately means aborting a measurement in progress — the SHT40 is mid-conversion and the I2C transaction may be in flight — to service a press whose meaning (OTA opt-in) is only valid at cold boot anyway. Latching it costs one bit and lets the machine finish the 10 ms it was already committed to. The general principle: a state that is 10 ms from completing should complete. Deferral is not procrastination, it is a way of keeping the number of partially-completed things at zero.

Timer during anything awake. A scheduled report timer that expires while the previous report is still being produced means the machine is running late, and queueing the extra report guarantees it falls further behind — each late report making the next one later. Discarding it is right: the tag reports on a fixed schedule, one report per wake, and if a cycle is missed the sequence number in the payload tells the gateway so. Backpressure by discarding, not by queueing, is the correct default for periodic telemetry, and it is a place where firmware and web engineering agree.

EXAMPLEWriting it in C, without ceremony

There are three common implementations: a nested switch, a table of function pointers, and a code generator fed by a diagram. For a six-state machine the nested switch wins outright — it is readable in one screen, it produces a trace for free, and there is nothing to keep in sync. Reach for a table when the machine grows past what one page can hold, and for a generator when a diagram is the artefact that the team actually maintains.

fsm.cBeacon's application task · one queue, one switch, no delays
typedef enum { ST_BOOT, ST_SELF_TEST, ST_SLEEP, ST_WAKE, ST_SAMPLE, ST_ADVERTISE } state_t;
typedef enum { EV_TIMER, EV_MOTION, EV_BUTTON, EV_SAMPLE_READY,
               EV_SENSOR_ERR, EV_ADV_DONE, EV_SELFTEST_DONE } event_t;

static const char *ST[] = { "BOOT","SELF_TEST","SLEEP","WAKE","SAMPLE","ADVERTISE" };
static const char *EV[] = { "TIMER","MOTION","BUTTON","SAMPLE_READY",
                              "SENSOR_ERR","ADV_DONE","SELFTEST_DONE" };

RTC_DATA_ATTR static uint8_t  moved;        // survives deep sleep (3.1)
RTC_DATA_ATTR static uint8_t  adv_seq;
static bool btn_pending;                        // awake-only: RAM is gone after sleep
static QueueHandle_t q_ev;                     // depth 8, filled by ISRs and timers (3.4)

static state_t step(state_t s, event_t e)
{
    ESP_LOGI(TAG, "%s + %s", ST[s], EV[e]);        // the trace IS the explanation (3.9)
    switch (s) {

    case ST_SELF_TEST:
        if (e == EV_BUTTON)        { ota_enter(); return ST_SELF_TEST; }   // 4.9
        if (e == EV_MOTION)        { moved = 1;   return ST_SELF_TEST; }
        if (e == EV_SELFTEST_DONE) return ST_SLEEP;
        return ST_SELF_TEST;                          // documented discard

    case ST_WAKE:
        if (e == EV_MOTION) { moved = 1; }
        if (e == EV_BUTTON) { btn_pending = true; }
        return ST_SAMPLE;   // WAKE is a pass-through: record the cause, then sample

    case ST_SAMPLE:
        if (e == EV_SAMPLE_READY) return ST_ADVERTISE;
        if (e == EV_SENSOR_ERR)   { report_flag(FLAG_T_STALE); return ST_ADVERTISE; }
        if (e == EV_MOTION)       { moved = 1; return ST_SAMPLE; }
        if (e == EV_BUTTON)       { btn_pending = true; return ST_SAMPLE; }
        return ST_SAMPLE;                             // TIMER lands here: discarded

    case ST_ADVERTISE:
        if (e == EV_ADV_DONE) return ST_SLEEP;
        if (e == EV_MOTION)   { moved = 1; return ST_ADVERTISE; }  // next report carries it
        if (e == EV_BUTTON)   { btn_pending = true; return ST_ADVERTISE; }
        return ST_ADVERTISE;

    default:
        return s;
    }
}

static void on_enter(state_t s)                    // entry work lives HERE, once
{
    switch (s) {
    case ST_SAMPLE:    sht40_trigger(&app.sht); esp_timer_start_once(t_conv, 8500); break;
    case ST_ADVERTISE: ble_adv_burst(build_payload(adv_seq++, moved)); moved = 0; break;
    case ST_SLEEP:     lis2dh12_clear_latch(&app.acc);      // or it wakes instantly (3.4)
                       esp_sleep_enable_timer_wakeup(60000000);
                       esp_deep_sleep_enable_gpio_wakeup(BIT(3), ESP_GPIO_WAKEUP_GPIO_HIGH);
                       esp_deep_sleep_start();               // never returns — the next
    default: break;                                  // boot IS the transition
    }
}

void app_main(void)
{
    state_t s = bootstrap();                       // wake cause → ST_WAKE, or ST_BOOT cold
    on_enter(s);
    event_t e;
    for (;;) {
        if (xQueueReceive(q_ev, &e, pdMS_TO_TICKS(5000)) == pdTRUE) {
            state_t next = step(s, e);
            if (next != s) { s = next; on_enter(s); }
        } else {
            ESP_LOGE(TAG, "stranded in %s for 5 s", ST[s]);   // the safety net
            buglog_note(BUG_STRANDED, s);                     // 3.9 / 6.7
            s = ST_SLEEP; on_enter(s);                        // go to sleep and live
        }
    }
}

Two features of that loop are worth more than the switch statement. The logged transition — state plus event, one line, at every step — turns the buglog partition into a narrative; when unit 9 comes back you read what it was doing rather than guessing. And the five-second queue timeout is a deliberate safety net for the bug this whole lesson is about: if the machine has been in any state for five seconds with nothing arriving, something was not handled, so record the state and sleep anyway. It converts "flat battery in four days, no evidence" into "one lost report, and a log entry naming the state". That is not a fix for a missing transition — nothing forgives a missing transition — but it is the difference between a defect you can find and a defect you can only theorise about.

✔ Why not a table of function pointers?

Because at six states it costs more than it gives. A handler_t table[6][7] is genuinely elegant, forces you to fill every cell, and is what you should build when a machine outgrows one screen. At this size it turns one readable function into forty-two named functions plus a table that must stay in step with two enums, and the compiler will not tell you when someone adds an event and leaves a row short. The switch version gets part of that back: enable -Wswitch-enum and the compiler complains about every state you did not mention. Be honest about the limit — the events inside each case are if chains, and no warning flag will tell you a state ignores an event. The compiler checks one axis of the table; the other one is still on you. Take the check from the tool, not from the architecture.

BEACONBeacon's FSM, fixed for firmware v0

The canonical machine, with the timing and energy each state is allowed to spend. The totals are the canon's: about 45 ms awake per scheduled report at 40 mA, roughly 8 µA asleep, which averages near 38 µA and gives a theoretical three years on a 1000 mAh cell — against R1's six-month requirement with a large derating margin.

StateEntered byEntry workBudgetLeaves on
BOOTPower-on, or any reset that is not a deep-sleep wakeClocks, pins (3.3), bus init and probe (3.5), driver init (3.6)~20 msImmediately → SELF_TEST
SELF_TESTBOOTIdentity checks on both sensors, one full sample, battery reading, LED on. Stays awake 2 s so the user can opt into OTA with the button.2 s, cold boot onlySELFTEST_DONE → SLEEP; BUTTON → OTA (4.9)
SLEEPSELF_TEST, ADVERTISE, or the stranded-state safety netClear the INT1 latch, arm the 60 s RTC timer and the GPIO3 wake, switch the battery divider on for the next cycle if this is the hourly one, deep sleep≈ 8 µAA wake, which is a reset
WAKERTC timer, motion on INT1, or (Rev B) the buttonRead the wake cause, restore RTC-memory state, bring up the bus~30 msImmediately → SAMPLE
SAMPLEWAKETrigger the SHT40, arm the 8.5 ms one-shot; read the accelerometer source register, and read the battery ADC on GPIO4 if the divider was left on before this sleep (see below)~10 msSAMPLE_READY or SENSOR_ERR → ADVERTISE
ADVERTISESAMPLEBuild the 14-byte payload, transmit the three-packet burst at 0 dBm, clear moved~5 msADV_DONE → SLEEP

A wait that does not fit the window. The battery divider is 2 × 1 MΩ with a 100 nF capacitor, so its Thévenin resistance is 500 kΩ and τ = 50 ms; five time constants is about 250 ms, which is more than five times the entire active window. There is no honest way to read it inside SAMPLE, and a busy-wait would cost 250 ms at 40 mA every minute — roughly six times the whole energy budget. The resolution needs no new state at all: the PMOS on GPIO1 switches the divider on as part of the SLEEP entry work on one cycle in sixty, and the ADC on GPIO4 is read at the start of the next SAMPLE, after which the divider goes off again. The settling happens during a deep sleep the device was taking anyway, the divider draws its 1.85 µA for one minute in sixty (about 0.03 µA averaged, against an 8 µA sleep budget), and the reported battery voltage in every minute's payload is the most recent value held in RTC memory. Whenever a required wait is longer than the state that needs it, look for a wait the system is already doing.

An honest note about WAKE(button). The machine above accepts a button wake, and the canon is explicit that Rev A cannot deliver one. That transition is unreachable on this hardware: the button is on GPIO9, which is not an RTC-domain pad and therefore cannot end a deep sleep (3.3). The code keeps the transition because it is correct, because Rev B moves the button to an RTC-domain pad that is not a strapping pin, and because a state machine that describes the intended device rather than one revision's compromise is easier to reason about than one riddled with hardware caveats. What the firmware must not do is rely on it: the OTA opt-in is served only in the cold-boot SELF_TEST window, and the user documentation says so.

🔑 Beacon firmware v0: what this lesson fixes

(1) One application task, one event queue of depth 8, one state machine; no delays anywhere in the application. (2) Forty-two filled cells: every state × event pair either transitions, acts, or is a documented discard. (3) moved and adv_seq live in RTC memory and survive deep sleep; everything else is rebuilt at every wake. (4) Entry work lives in on_enter(), so clearing the interrupt latch before sleep cannot be forgotten by a new code path. (5) Every transition is logged as state + event; the five-second stranded-state timeout records the state and sleeps rather than burning the battery. (6) Motion during ADVERTISE sets the flag for the next report; a button during SAMPLE is latched; a redundant report timer is discarded.

WEAKNESSWhere this bites

✗ The blank cell that looks like nothing

A missing transition is invisible: there is no code to review, no warning to enable, no test that fails. It surfaces as a device that is neither crashed nor working, which is the hardest state to diagnose because a watchdog will not fire (the loop is running fine, waiting on a queue) and the logs end without an error. Three defences, in order of value. Build the table before the code and keep it in the repository next to the source. Turn on -Wswitch-enum so the compiler names every enumerator you did not mention. And add the stranded-state timeout, which does not fix the omission but converts a silent battery death into a log entry naming the state — the difference between a bug you can find in an hour and one you cannot reproduce at all.

✗ Doing the work inside the transition

The state machine can only process one event at a time, so any blocking call inside a transition blocks the entire application: events pile up in the queue, the queue fills, and xQueueSendFromISR starts dropping motion events (3.4). The seductive version is a driver call that "usually takes 2 ms" and occasionally takes its full 20 ms timeout twice over. The rule that keeps you honest: a transition may start work and arm a timer, but it may never wait for work to finish. That is why the SHT40 driver is split into trigger and fetch (3.6), and why the advertising burst signals completion with an event rather than a return value.

✗ Turning facts into states

The fastest way to make people hate state machines is to add SAMPLE_WITH_LOW_BATTERY, SAMPLE_AFTER_MOTION, and SAMPLE_WITH_STALE_SENSOR. Now the table has thirty states, most transitions are duplicated across near-identical rows, and the next person adds a flag to avoid adding a state, which is the implicit machine all over again. States are modes of operation; conditions are variables that transitions read. moved, btn_pending, and the stale flag are all variables in Beacon precisely because none of them changes what the device is doing — only what it puts in the payload. If a condition genuinely changes the machine's structure (OTA mode does), it earns a state. If it changes a value, it is a variable.

KEY INSIGHTHow this connects

  • Interrupts, Polling, and the Latency Budget (3.4) — the ISR that captures a timestamp and queues an event is the machine's input; the queue depth is the machine's tolerance for a burst.
  • Writing Drivers and Hardware Abstraction (3.6) — trigger and fetch are separate functions so that SAMPLE can be a state rather than a blocked call, and the driver's error return is a transition, not an exception.
  • FreeRTOS Essentials (3.8) — next: what the single task in this lesson is competing with, why the BLE stack's own tasks matter, and when splitting this machine across several tasks would be an improvement rather than a hazard.
  • Debugging Firmware (3.9) — the transition log and the stranded-state note become the evidence; the reset-reason register tells you which of the six states you were in when the world ended.
  • Sleep Modes and Wake Sources (4.3) — the SLEEP state's entry work is elaborated into the real energy analysis, where the 8 µA is measured rather than asserted.

The transferable habit is the table. Before writing the loop, write the grid — states down, events across — and fill every cell, out loud, with a colleague if you can find one. The cells you argue about are the design; the cells you would have left blank are the field returns.

GLOSSARYKey terms introduced

Finite state machine (FSM)
A design in which the system is always in exactly one of a small set of states, and every event is handled by a defined transition from the current state. Its value comes from completeness, not from the diagram.
Transition table
The states × events grid. Every cell must contain a decision — change state, act and stay, or explicitly discard. Blank cells are the defect this lesson exists to prevent.
Entry / exit action
Work performed whenever a state is entered or left, written once at the state boundary rather than at each call site. Clearing the accelerometer's interrupt latch before deep sleep is Beacon's example.
Documented discard
An event that a state deliberately ignores, with the reason recorded. Functionally similar to a blank cell and completely different in practice, because a reader can tell that somebody thought about it.
Stranded state
A state whose only exit is an event that will not arrive, usually because it was delivered while the machine was elsewhere. The device is not crashed and not working, and on battery power it is fatal.
Superloop
A while(1) containing the whole application, typically with delays. Excellent for bring-up; becomes an undocumented state machine the moment anything must happen during a delay.
RTC memory
The small always-on memory that survives deep sleep. Variables marked RTC_DATA_ATTR live there; on the ESP32-C3 everything else is lost at every wake, because a wake is a reset.
Backpressure by discarding
Dropping a redundant periodic event rather than queueing it, so that a late system catches up instead of falling further behind. The right default for fixed-rate telemetry.

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1Motion is detected while the tag is mid-advertising-burst. Three designs are proposed: abort and re-sample; queue a second report; set a flag for the next report. Argue for one.›

Set the flag. Aborting throws away energy already spent, risks the gateway receiving a partial report, and — the decisive objection — produces a livelock on a moving asset: a tag on a trolley being pushed down a corridor would restart its report on every bump and never transmit at all. Queueing a second report is nearly as bad: each extra report costs a full wake window at 40 mA, and continuous motion turns a 38 µA average into something the battery cannot support, which is R1 failing quietly. Setting moved in RTC memory costs one bit, lets the burst finish, and carries the fact to the next report. The latency cost is at most one cycle, and it is not even that in practice, because the motion interrupt also causes its own wake — so the "next report" is usually seconds away, well inside R4's two-second budget.

2A tag is found awake with a flat battery. The log's last line is SAMPLE → ADVERTISE. No panic, no watchdog reset. What happened, and which two mechanisms would have turned this into a finding instead of a mystery?›

The machine entered ADVERTISE and the ADV_DONE event either never arrived or arrived in a state that discarded it, so ADVERTISE had no exit. The application was not crashed — its loop was running, blocked on an empty queue — so no watchdog fired, and the radio and CPU stayed powered at roughly 40 mA until a 1000 mAh cell was empty, about a day. The two mechanisms: first, the five-second stranded-state timeout on the queue receive, which records the state to the buglog partition and forces a transition to SLEEP, costing one report instead of the whole battery; second, the logged transition line for every state and event, which is what lets you see that ADV_DONE never appeared rather than inferring it. Neither is a substitute for filling in the transition table, but together they convert a silent four-day death into a log entry naming the state.

3Why is entering deep sleep implemented as entry work for the SLEEP state rather than as a call at the end of the ADVERTISE handler? And why does the code comment say the function never returns?›

Because there is more than one way into SLEEP — from SELF_TEST at cold boot, from ADVERTISE at the end of a normal cycle, and from the stranded-state safety net — and each path must do the same three things: clear the LIS2DH12's latched interrupt (or the chip wakes immediately and forever, 3.4), arm the RTC timer and the GPIO wake, then sleep. Putting that at the state boundary means it happens once, correctly, for every path including ones added later. esp_deep_sleep_start() never returns because deep sleep powers down the digital core: there is no stack to come back to. The next thing that executes is the ROM at the next reset, so the "return" from sleep is a fresh app_main that reads esp_sleep_get_wakeup_cause() and re-enters the machine at WAKE, with only the RTC-memory variables carried across.

4A colleague wants to add three states — SAMPLE_LOW_BATTERY, SAMPLE_AFTER_MOTION, and SAMPLE_STALE — so the code can "handle each case properly". What is wrong with this, and what is the test for whether something deserves to be a state?›

Those are conditions, not modes of operation. The device is doing exactly the same thing in all three — triggering a sensor and waiting for a conversion — so the rows of the transition table would be near-identical duplicates, and every future event would have to be handled three times with three chances to differ. The table would grow from 42 cells to well over a hundred, most of them copies, and the next person will avoid adding a state by adding a flag, which is the implicit state machine returning by the back door. The test: does this change what the device is doing, or only what it records? Low battery, recent motion, and a stale reading all change values in the payload, so they are variables that transitions read. OTA mode changes what the device does — different peripherals, different power state, different events entirely — so it earns a state. Keep the state count small enough to fit on one page and put the nuance in variables.

Next: an RTOS gives you tasks, and priority inversion →