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

Interrupts, Polling, and the Latency Budget

An interrupt is a promise to stop what you are doing. Keep it short or you break every other promise.

⏱ ~25 min read ⚠ The 3.5 ms ISR 🔧 esp_intr_alloc · gpio_isr_handler_add · FromISR

🎯 By the end you'll understand

What the hardware actually does between a rising edge on a pin and the first line of your handler, and which parts of that delay you can shorten. Why the length of an interrupt service routine is a property of the whole system rather than of the routine, with the arithmetic to prove it: one log line inside an ISR costs 3.5 ms on a 115200-baud console. How to defer work correctly with a queue, a task notification, or a flag, and why volatile answers a question about the compiler and not about atomicity. When polling beats interrupting. And how Beacon's LIS2DH12 motion path meets requirement R4's two-second budget with an order of magnitude to spare, which turns out not to be the reason to keep the ISR short.

KEY INSIGHTAn ISR spends other people's time

Yesterday's build reported every minute for eleven hours without a fault. Today, roughly one report in four carries a temperature of exactly −45.00 °C and the log says i2c: transaction timeout. Nothing about the sensor changed, the wiring is untouched, and the bench power supply reads the same current. The diff is one line: a log statement added to the motion interrupt handler so somebody could count shakes.

−45.00 °C is not a temperature; it is the SHT40's conversion formula applied to a buffer of zeros, because the read failed and the driver returned a zeroed struct. The log line is not innocent either: ESP_EARLY_LOGI writes to the console with a busy-wait, and at 115200 baud each byte takes ten bit times, which is 86.8 µs. A forty-character line is 3.47 ms spent inside an interrupt handler with the scheduler suspended and every other interrupt of equal or lower priority held off. That is the entire bug: not a wrong value, not a broken sensor, but an interrupt that decided it deserved 3.47 ms of a system whose whole active window is 45 ms.

🔑 Hold onto this

The cost of an ISR is not its own runtime; it is its runtime multiplied by how often the hardware fires it, subtracted from every other deadline in the system. A 3.47 ms handler is harmless at one event per minute and fatal at one event every 2.5 ms — and the accelerometer's output data rate, a register you set in a different file on a different day, is what decides which of those you have. Write the handler as though the event rate could be a hundred times what you expect, because a sensor on a shaking asset is exactly that.

HOW IT WORKSBetween the edge and your code

An interrupt is not magic and it is not instantaneous. Between the physical edge on the pad and the first instruction of your handler there is a fixed pipeline, and every stage of it costs time. Knowing the stages tells you which delays you can shorten (your handler, the dispatcher you chose) and which you cannot (synchronisation, context save).

INT1 edge pad synchroniser 2 APB clocks GPIO status bit latched, sticky interrupt matrix priority 1–15 trap + context registers pushed GPIO dispatcher → your handler latency you cannot shorten — hardware and the port (≈ 1–3 µs, measure yours) duration you own 3 µs or 3,470 µs — your choice Everything to the left is fixed cost. Everything to the right is a decision you make in one function.
The interrupt path on an ESP32-C3. The pin edge is synchronised to the APB clock, latched in a sticky status register, routed by the interrupt matrix to a CPU interrupt line with a priority, and trapped; only then does software run — first ESP-IDF's vector code, then the shared GPIO dispatcher, then your per-pin callback.

Four things about that path are specific to the ESP32-C3 and change how you design:

FactMechanismWhat it forces on your design
All GPIO pins share one interrupt sourceThe GPIO peripheral raises a single interrupt; ESP-IDF's gpio_install_isr_service() registers one handler that reads the status register and calls the per-pin callbacks you added with gpio_isr_handler_add()Per-pin "priority" does not exist. A slow handler on the button pin delays the handler on the accelerometer pin. Both are the same interrupt.
One coreThe C3 is a single RISC-V core at 160 MHz (3.1)There is no "pin it to core 1" escape hatch. Time spent in an ISR is time no task anywhere gets. This is the honest cost of the single-core choice from Lesson 1.6.
Priorities are numbers, not tiers of codeThe interrupt matrix assigns each source a priority level; esp_intr_alloc() takes ESP_INTR_FLAG_LEVEL1…LEVEL3. A higher-priority source can interrupt a lower-priority handlerRaising a handler's priority does not make it shorter. It only moves the pain onto whatever you demoted.
Flash is a cache, and the cache can be offCode lives in flash and is fetched through a cache. Writing flash (an OTA chunk, an NVS commit) disables that cache for the durationAn ISR that must run during a flash write has to live in internal RAM: IRAM_ATTR on the function, ESP_INTR_FLAG_IRAM on the allocation, and every function it calls in IRAM too.

The last row is the one that produces the most confusing field failures, because the symptom is a panic with no obvious relationship to the interrupt. The chip fetches an instruction from a flash address while the cache is disabled, the memory-protection logic raises a cache error, and the panic handler prints a message naming the cache rather than naming your handler. It reproduces only when an interrupt happens to land inside the few milliseconds of a flash write, so it survives every bench test and appears in the field at a rate proportional to how much the device is moved.

📖 Interrupt latency, defined properly

Interrupt latency is the time from the hardware event to the first instruction of the handler. Interrupt response time is the time to the point where the work is actually done, which for a well-written system means the time to when the task woken by the ISR runs. The two differ by whatever deferral mechanism you chose, and it is the second number that matters to a requirement like Beacon's R4. Quoting the first number to a customer is a way of being technically correct and practically wrong.

IN PRACTICEFive rules and the mechanism behind each

Every ISR rule you have read as a bullet point has a mechanism underneath it. Learn the mechanism and you can tell when the rule bends.

1

Short. Measured in microseconds, not milliseconds.

Because the cost is duration × rate, and the rate belongs to the outside world. Budget the handler against the fastest the source can fire, not the fastest you expect it to fire. Beacon's accelerometer at 25 Hz gives 40 ms between edges; the same part configured at 400 Hz gives 2.5 ms, and a 3.47 ms handler then never finishes before the next one arrives.

2

No blocking calls. Not "avoid" — cannot.

Because blocking means taking a semaphore or a mutex, and FreeRTOS's blocking primitives assert when called from an interrupt context. i2c_master_transmit() takes a bus mutex internally, so reading the accelerometer's interrupt-source register from the handler does not run slowly — it aborts the firmware. Use the …FromISR variants, which never block, and check their return value.

3

No logging. Even the "ISR-safe" logging.

Because ESP_LOGI is not ISR-safe at all (it takes a lock and formats through the C library), and ESP_EARLY_LOGI, which is callable from an ISR, gets there by busy-waiting on the console: 86.8 µs per byte at 115200 baud. On the native USB Serial/JTAG console the cost is different but not smaller, because the routine waits for space in an endpoint the host polls once per USB frame, which is once per millisecond. If you must mark an event, increment a counter and print it from a task.

4

Share state carefully. volatile is not a synchronisation primitive.

Because volatile tells the compiler not to cache the value in a register or reorder the access; it says nothing about whether the access is a single instruction. A 32-bit aligned word on a 32-bit core is naturally atomic; a uint64_t timestamp is two stores, and a reader can catch it half-written. Use a queue, or a 32-bit word, or a spinlock via portENTER_CRITICAL_ISR().

5

Clear the source, and know whether it latches.

Because a level-triggered interrupt whose cause is still asserted re-enters the handler immediately and forever. The ESP32-C3's GPIO status bits are sticky and ESP-IDF's dispatcher clears them for you; the sensor's interrupt is a separate matter. The LIS2DH12 with latching enabled holds INT1 high until you read INT1_SRC over I2C, which you cannot do from the ISR (see rule 2), so the clearing belongs in the task.

motion.cESP-IDF 5.x · the whole handler, and why it is this short
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "esp_timer.h"

#define PIN_ACC_INT 3          // LIS2DH12 INT1, RTC-capable pad (3.3)

typedef struct { uint32_t us_lo; uint8_t src; } motion_evt_t;

static QueueHandle_t q_evt;      // depth 8, created in app_main before the ISR is armed
static portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
static volatile uint32_t motion_count;   // 32-bit: one aligned store, naturally atomic

static void IRAM_ATTR motion_isr(void *arg)          // IRAM: survives an NVS/OTA flash write
{
    motion_evt_t e = { .us_lo = (uint32_t)esp_timer_get_time(), .src = 1 };
    motion_count++;                                  // single 32-bit RMW, ISR is the only writer

    BaseType_t hpw = pdFALSE;
    xQueueSendFromISR(q_evt, &e, &hpw);              // never blocks; returns errQUEUE_FULL if full
    if (hpw == pdTRUE) portYIELD_FROM_ISR();          // wake the app task now, not at the next tick
}                                                     // ≈ 6 µs. That is the whole job.

void motion_isr_install(void)
{
    q_evt = xQueueCreate(8, sizeof(motion_evt_t));
    ESP_ERROR_CHECK(gpio_install_isr_service(ESP_INTR_FLAG_IRAM));   // one service, all pins
    ESP_ERROR_CHECK(gpio_isr_handler_add(PIN_ACC_INT, motion_isr, NULL));
}

Read what is not in that handler. It does not read the accelerometer to find out which axis tripped — that is an I2C transaction, and I2C from an ISR aborts. It does not log. It does not decide anything: no threshold comparison, no state transition, no "if this is the third event in a second". It captures the one piece of information that will be gone by the time anyone else looks — the timestamp — and it tells somebody. The 64-bit microsecond counter is truncated to its low 32 bits on purpose: a 32-bit store is atomic on this core, and 32 bits of microseconds wraps every 71.6 minutes, which is far longer than the milliseconds between the capture and its use. That is a deliberate, documented narrowing, not an accident.

✔ The one-line test for an ISR

Read your handler and ask: what does this line know that nothing else can find out later? A timestamp qualifies. A hardware FIFO that will overflow qualifies. A status register that is cleared by reading qualifies. Everything else — decoding, filtering, deciding, logging, reacting — can be done a millisecond later by a task, and a task is a place where you are allowed to be slow, allowed to block, and allowed to be wrong without taking the system down with you.

SEE ITLatency budget simulator: fifty milliseconds of Beacon's life

The scenario is one wake window. An I2C read of the SHT40 is in flight at 4 ms. At 30 ms the firmware commits its sequence number to the NVS partition, which disables the instruction cache for about eight milliseconds. Meanwhile the LIS2DH12's INT1 pin is firing at whatever rate its output-data-rate register was left at. You choose what the handler does, how the work reaches the application, how the shared timestamp is declared, and where the handler lives. The timeline is computed from those choices, and every one of them can break something different.

⚙ Interactive · ISR duration, deferral, and what breaks

Deterministic model. The 3,470 µs figure is arithmetic: 40 characters × 10 bit-times ÷ 115200 baud. The 6 µs and 25 µs handler figures and the 8 ms cache-off window are budget estimates of the right order, labelled as such — measure your own with a GPIO toggle and a scope (3.9). The I2C call's timeout is set to 20 ms by the driver in 3.6.

INT1 ISR I2C flash app milliseconds after wake
ISR duration
—
CPU inside ISRs
—
Motion → handled
—

    Three things are worth provoking deliberately. Set the handler to the I2C read and nothing else matters: the firmware aborts on the first edge, because a blocking call in an interrupt context is not slow, it is illegal. Set the handler to the log line and the output data rate to 400 Hz: the handler takes longer than the gap between events, so the core re-enters it forever, the I2C transaction never completes, and the tag stays awake until the battery dies — the failure mode Lesson 3.7 will call a stranded state. And take the correct 6 µs handler, leave it out of IRAM, and watch it work perfectly at 25 Hz and crash at 100 Hz, because at 100 Hz an edge finally lands inside the flash write. That last one is the shape of a real field bug: correct code, correct logic, wrong memory.

    CORE CONCEPTDeferring the work: three mechanisms and a debounce

    Every interrupt design is really a two-part design: a tiny top half in interrupt context, and a bottom half in task context where the actual work happens. ESP-IDF gives you three ways to get from one to the other, and they differ in cost, in capacity, and in what they lose.

    MechanismCost in the ISRCapacityWhat it losesUse for
    volatile flag + polling loopA single store, ~1 µsOne bit. Ten events in one poll period look identical to one.Counts and timestamps; latency up to one poll periodA rare event whose only meaning is "something happened", in a loop that runs anyway
    xQueueSendFromISR()~5–10 µs (estimate; measure)The depth you allocated. Full means errQUEUE_FULL and a dropped event, silently if you ignore the return value.Nothing, until it is fullEvents that carry data — a timestamp, an axis, an ADC reading
    xTaskNotifyFromISR()Cheapest of the three; no queue objectOne 32-bit word per task, used as a counter or bit setPayload. You get a count or bits, not a struct."Wake up, there are N of them" — the common case

    All three end with the same two lines: set a BaseType_t to pdFALSE, pass its address, and call portYIELD_FROM_ISR() if the call set it true. That flag means "the task I just made ready has a higher priority than the one that was running", and the yield performs the context switch on the way out of the interrupt instead of at the next scheduler tick. Forget it and your carefully measured 6 µs handler is followed by up to 10 ms of the wrong task running, which is the entire latency you were trying to avoid.

    Debouncing. A mechanical button does not make one edge; it makes a burst of them over a few milliseconds as the contacts settle. On Beacon's GPIO9 button (3.3) an edge-triggered interrupt therefore fires five or ten times per press, and if each one queues an event, the application sees a press, a release, and three more presses. There are two honest fixes and one popular non-fix:

    ApproachWhat it doesCostVerdict
    RC filter + Schmitt-trigger inputA 10 kΩ / 100 nF network in front of the pin turns the bounce into one slow edge; the input's hysteresis turns it back into one clean digital edgeTwo parts, board area, and 1 ms of intentional delayCorrect, and it works before any code runs
    Edge interrupt + one-shot timerThe ISR queues the first edge and starts a 20 ms esp_timer; further edges within the window are ignored; the timer callback samples the pin's level and reports the settled stateTwenty lines of firmware, zero partsBeacon's choice. Sampling the level at the end is what makes it robust rather than merely quieter.
    vTaskDelay(pdMS_TO_TICKS(20)) inside the ISRNothing. It asserts.A crashThe rule-2 violation that people reach for first
    button.cdebounce without blocking, and without losing the press
    #define PIN_BUTTON      9
    #define DEBOUNCE_US 20000       // 20 ms — longer than any bounce we measured on the scope
    
    static esp_timer_handle_t debounce_t;
    static volatile bool settling;      // 1-byte flag, ISR writes, timer reads
    
    static void IRAM_ATTR button_isr(void *arg)
    {
        if (settling) return;                    // bounce edges 2..N: drop, cheaply
        settling = true;
        esp_timer_start_once(debounce_t, DEBOUNCE_US);   // ISR-safe; does not block
    }
    
    static void debounce_done(void *arg)          // task context: allowed to be slow
    {
        int level = gpio_get_level(PIN_BUTTON);    // sample the SETTLED state, not the edge
        settling = false;
        if (level == 0) fsm_post(EV_BUTTON);       // active-low: a real press (3.7)
        else            fsm_post(EV_BUTTON_UP);
    }

    The subtlety is the last three lines. A debouncer that only suppresses extra edges still reports whatever the first edge said, and the first edge of a bounce burst can be a false one caused by vibration or ESD. Sampling the level after the settling window asks the pin what is actually true now, which costs nothing and turns a filter into a measurement. The same pattern debounces the reed switch, the lid sensor, and the connector-detect pin on every product you will ever build.

    COMPARISONWhen polling is the right answer

    Interrupts have a reputation as the grown-up choice and polling as the beginner's. That is backwards often enough to be worth stating plainly: polling is deterministic, has no shared-state hazards, no ISR rules, no priority questions, and no latency variance. It costs CPU time you might have spent sleeping — which on a battery-powered device is the whole objection, and on a device that is awake anyway is not an objection at all.

    SignalBeacon's choiceWhy
    SHT40 measurement completePolled — a one-shot timer fires at 8.5 ms and the task readsThe delay is specified in the datasheet and does not vary. The sensor has no interrupt pin. An interrupt would be a fiction wrapped around a known constant.
    LIS2DH12 motionInterrupt on INT1The event is rare, asynchronous, and the whole point is to be asleep until it happens. Polling it would mean waking every 40 ms to ask, which is roughly a thousand times more energy than sleeping (R1).
    User buttonInterrupt while awake, ignored while asleepRare and asynchronous, but GPIO9 cannot wake the chip (3.3), so while asleep the button is not polled or interrupted — it simply does not exist.
    Battery voltage (divider on GPIO4, ADC1_CH4)Polled — but not inside the wake that switches it onIt changes over hours, so there is no event to interrupt on. The catch is the divider itself: 2 × 1 MΩ with 100 nF gives a Thévenin resistance of 500 kΩ and τ = 50 ms, so it needs about 250 ms to settle — five times the entire active window. The PMOS on GPIO1 switches the divider on at the end of one wake and the ADC is read at the start of the next, so the settling happens inside a deep sleep the device was taking anyway. Never a busy-wait.
    BLE advertising completeCallback from the host stack (an interrupt underneath)You do not get a choice; the controller's interrupt is part of the stack you did not write (3.8).
    🧪 The energy argument, with Beacon's numbers

    Suppose you replaced the motion interrupt with polling: wake every 40 ms, read the accelerometer, sleep again. Each wake costs roughly the same fixed overhead as a report wake, and the canon's active window is 45 ms at 40 mA. Even at a tenth of that per poll — 4.5 ms at 40 mA, once per 40 ms — the average is about 4.5 mA, which drains a 1000 mAh cell in roughly nine days. The interrupt path costs 8 µA while waiting. That factor of five hundred is why a motion-wake pin exists on the sensor at all, and it is the clearest example in this course of a hardware feature that only pays off if the firmware is written to use it.

    The dishonest version of this argument is "interrupts are more efficient". They are not, intrinsically. An interrupt that fires at 400 Hz into a 3.47 ms handler is vastly less efficient than a 1 Hz poll. Efficiency comes from the ratio of useful work to wake-ups, and the design question is always the same: is the event rare and unpredictable (interrupt), or frequent and scheduled (poll)?

    BEACONThe motion path, and the budget it has to meet

    Requirement R4 says a report must reach the gateway within two seconds of motion. Here is the whole chain with the canon's numbers, marked where a figure is measured, budgeted, or from a datasheet. The purpose of writing it out is not to prove the requirement is met — it is met by a wide margin — but to find out which link would break first if something changed.

    #Link in the chainTimeSourceWhat would break it
    1Movement exceeds the threshold; the LIS2DH12 compares at its output data rate of 25 Hz≤ 40 msDatasheet: one ODR periodA lower ODR to save current: 10 Hz makes this 100 ms and R3's "motion wake ≤ 100 ms" fails on its own
    2INT1_DURATION requires the condition to persist for 1 sample before asserting INT140 msRegister setting (Beacon: 1)Raising it to filter taps: each count adds one ODR period
    3INT1 rises; the pad wakes the chip from deep sleep; ROM and bootloader runtens of msBudgeted inside the canon's 45 ms active windowTurning off CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP, which makes the bootloader re-verify the whole app image on every wake
    4Sample: I2C read of the accelerometer source register and the SHT40 measurement≈ 10 msSHT40 high-precision conversion (datasheet: 8.2 ms max) plus two short I2C transactionsA retry loop with no bound (3.6)
    5Advertise: one BLE advertising event, three packets on channels 37/38/39a few msCanon: 3 packets per burstWaiting for a connection instead of advertising non-connectably (4.6)
    6Gateway receives and publishes over MQTTnot oursOut of scopeA gateway scanning with a low duty cycle — the most likely real-world cause of a missed report
    Total inside Beacon≈ 150 ms budgetedSum of 1–5R4 allows 2,000 ms. Margin ≈ 13×.

    Now the useful conclusion, and it is a contrarian one. Nothing in this chain is under latency pressure. A 3.47 ms ISR does not threaten R4; you could afford five hundred of them. The reason Beacon's handler is 6 µs is not latency at all — it is that a long handler stalls the I2C transaction that link 4 depends on, blows the 45 ms active window that R1's battery arithmetic assumes, and at a high event rate stops the state machine from ever reaching SLEEP. Latency requirements are the reason people give for short ISRs; energy and correctness are the reasons that actually apply here. Knowing which of your constraints is really binding is most of engineering judgement.

    lis2dh12_int.carming the motion interrupt · registers from the LIS2DH12 datasheet
    // Register map (auto-increment for multi-byte access needs bit 7 of the sub-address set)
    #define REG_CTRL1      0x20   // ODR + axis enables + low-power mode
    #define REG_CTRL3      0x22   // interrupt routing to the INT1 pin
    #define REG_CTRL5      0x24   // LIR_INT1: latch the interrupt until INT1_SRC is read
    #define REG_INT1_CFG   0x30
    #define REG_INT1_SRC   0x31   // reading this clears a latched interrupt
    #define REG_INT1_THS   0x32   // LSB = 16 mg at the ±2 g full scale
    #define REG_INT1_DUR   0x33   // in ODR periods
    
    static esp_err_t motion_arm(i2c_master_dev_handle_t acc)
    {
        // 25 Hz, low-power mode, all three axes: 0b0011 1 111 = 0x3F
        ESP_RETURN_ON_ERROR(reg_write(acc, REG_CTRL1,    0x3F), TAG, "ctrl1");
        // latch INT1 so a short bump is not missed between the edge and the read
        ESP_RETURN_ON_ERROR(reg_write(acc, REG_CTRL5,    0x08), TAG, "ctrl5");
        ESP_RETURN_ON_ERROR(reg_write(acc, REG_INT1_THS, 0x10), TAG, "ths");   // 16 × 16 mg = 256 mg
        ESP_RETURN_ON_ERROR(reg_write(acc, REG_INT1_DUR, 0x01), TAG, "dur");   // 1 sample = 40 ms
        // X/Y/Z high-event OR: 0b0010 1010 = 0x2A
        ESP_RETURN_ON_ERROR(reg_write(acc, REG_INT1_CFG, 0x2A), TAG, "cfg");
        // route IA1 to the physical INT1 pin
        ESP_RETURN_ON_ERROR(reg_write(acc, REG_CTRL3,    0x40), TAG, "ctrl3");
    
        uint8_t dummy;
        return reg_read(acc, REG_INT1_SRC, &dummy, 1);   // clear any stale latch before sleeping
    }

    The last line is the difference between a tag that sleeps and a tag that does not. With latching enabled, INT1 stays high until INT1_SRC is read. Go to sleep with the pin already high and configure a level-high wake source, and the chip wakes immediately, forever, at 40 mA. Clearing the latch before arming the wake is a one-line habit that prevents a class of bug whose only symptom is a battery that lasted four hours.

    🔑 Beacon firmware v0: what this lesson fixes

    (1) One GPIO ISR service, installed with ESP_INTR_FLAG_IRAM; every handler is IRAM_ATTR and calls only IRAM-safe functions. (2) The motion handler is a timestamp, a 32-bit counter, and a queue send — no I2C, no logging, no decisions. (3) The queue is depth 8 and its return value is checked; a dropped event increments a diagnostic counter that ends up in the buglog partition (3.9). (4) The button is debounced with a 20 ms esp_timer one-shot that samples the settled level. (5) The accelerometer runs at 25 Hz with a 256 mg threshold and a 1-sample duration, and the latch is cleared before every sleep.

    WEAKNESSWhere this bites

    ✗ "One little log line in the ISR, just for debugging"

    It is never little. ESP_EARLY_LOGI busy-waits on the console: 86.8 µs per character at 115200 baud, so a modest line is milliseconds. Worse, it is a Heisenbug generator — the delay it adds often changes the timing enough to hide the very race you are chasing, so the bug "goes away when I add logging" and returns when you remove it. The correct instrument is a GPIO toggle at the top and bottom of the handler and a scope or logic analyser across the pin: it costs about 200 ns, it does not perturb what you are measuring, and it gives you the distribution of durations rather than one anecdote. Lesson 3.9 makes this the standard technique.

    ✗ "It's volatile, so it's safe to share"

    volatile makes the compiler re-read the variable from memory and stops it reordering the access. It does not make an access atomic, and it does not create a memory barrier between two variables. Three specific ways this bites on a 32-bit core: a uint64_t timestamp is two stores, so a reader can see the high half of the new value with the low half of the old one — a timestamp 4,294 seconds in the future, which makes a "time since last event" calculation negative and the state machine's timeout arithmetic nonsense. A count++ shared by an ISR and a task is a read-modify-write that can lose an increment. And a pair of variables written in one order by the ISR can be observed in either order by the task unless something enforces the ordering. The fixes are boring: keep shared state to one naturally aligned 32-bit word, or pass it through a queue, or wrap both sides in portENTER_CRITICAL_ISR() / portENTER_CRITICAL() with the same spinlock.

    ✗ "With an interrupt I can't miss an event"

    You can, in two ways. First, coalescing: the GPIO status bit is a bit, not a counter. Two edges arriving before the handler runs set the same bit and produce one call. If you are counting steps, pulses, or coins, an interrupt gives you a lower bound, not a count — use a hardware counter (the pulse-counter peripheral, or a timer in capture mode) when the count itself is the data. Second, the queue you sent it to was full. xQueueSendFromISR() returns errQUEUE_FULL and, if you ignored the return value as most example code does, the event is gone with no trace. Check it, count the failures, and report the counter — a system that drops events and knows it is debuggable; one that drops events silently is not.

    KEY INSIGHTHow this connects

    • GPIO, Timers, and PWM (3.3) — the pin configuration that set intr_type, the RTC-domain restriction that puts INT1 on GPIO3, and the esp_timer one-shot reappear here as an interrupt source, a wake source, and a debouncer.
    • Serial Buses: UART, I2C, and SPI (3.5) — next: the I2C transaction that a long ISR stalls, seen at the level of clock edges and acknowledgements, including what a stuck bus looks like and how to recover it.
    • Writing Drivers and Hardware Abstraction (3.6) — the accelerometer register writes above become a driver with timeouts, retries, and error returns, and the queue this lesson fills becomes the driver's input.
    • State Machines and Event-Driven Firmware (3.7) — fsm_post(EV_BUTTON) and fsm_post(EV_MOTION) are the events; there they meet the states, including the awkward case of motion arriving while the tag is already advertising.
    • FreeRTOS Essentials (3.8) — portYIELD_FROM_ISR(), task priorities, and queue depth are RTOS concepts used here on trust and explained there in full.

    The habit to carry forward: when you write an interrupt handler, write down next to it the fastest rate the source can fire and multiply. If the product is more than a few percent of your CPU, you have not written a handler, you have written a scheduler for one very rude task.

    GLOSSARYKey terms introduced

    Interrupt service routine (ISR)
    The function the hardware calls in interrupt context. It runs with the scheduler suspended and equal-or-lower-priority interrupts masked, so its duration is subtracted from every other deadline.
    Interrupt latency vs response time
    Latency is event → first instruction of the handler; response time is event → the work actually being done. Deferral mechanisms move cost from the first to the second, which is usually the right trade.
    Top half / bottom half
    The split between the minimal work that must happen in interrupt context (capture what will be lost) and the rest, done in a task. Also called deferred processing.
    IRAM_ATTR
    An attribute placing a function in internal RAM rather than flash, so it can execute while the instruction cache is disabled — which it is during any flash write. Required for interrupts allocated with ESP_INTR_FLAG_IRAM, and it applies to everything the handler calls.
    Critical section / spinlock
    portENTER_CRITICAL() and portENTER_CRITICAL_ISR() briefly mask interrupts around an access to shared state, making a multi-word update indivisible. Correct, and expensive if held for more than a few microseconds.
    Coalescing
    Multiple hardware events collapsing into one handler call because the pending indication is a single latched bit. The reason an interrupt counts events unreliably.
    Edge vs level triggered
    An edge interrupt fires on a transition and latches; a level interrupt fires while the condition holds and re-fires until the source is cleared. A level interrupt whose source is cleared over a slow bus needs the clearing done in a task.
    Debounce
    Suppressing the burst of edges a mechanical contact produces, either with an RC filter and hysteresis in hardware or a timer plus a level sample in firmware. Sampling the settled level, not the first edge, is what makes it correct.

    ACTIVE RECALLCheck your understanding

    Answer in your own words first, then reveal.

    1A colleague defends a 3.5 ms ISR by pointing out that Beacon's motion requirement (R4) allows two full seconds. Why is that defence wrong, and what are the three things the long handler actually breaks?›

    The defence confuses latency with occupancy. R4 is met with roughly thirteen times margin, so latency is not the binding constraint — but the handler's cost is duration × rate, and it is subtracted from everything else. It breaks: (1) the I2C transaction in flight, which stalls for the duration of the handler and, at a high event rate, exceeds the driver's transfer timeout and returns zeros that decode to −45.00 °C; (2) the energy budget, because the canon's 45 ms active window at 40 mA is what makes R1's six-month life work, and milliseconds of extra awake time per event are a direct multiplier on average current; (3) liveness, because if the handler is longer than the interval between events — 3.47 ms against 2.5 ms at a 400 Hz output data rate — the core never leaves interrupt context, the state machine never reaches SLEEP, and the tag stays awake until the battery dies.

    2The motion handler stores a 64-bit microsecond timestamp in a volatile uint64_t that the application task reads. The task occasionally computes a time-since-last-motion of about −4,295 seconds. Explain, and give two fixes.›

    A 64-bit store on a 32-bit core is two instructions. If the interrupt lands between the task's two loads, the task reads the new low word with the old high word (or the reverse), producing a value off by 232 microseconds — 4,295 seconds, which is exactly the magnitude observed. volatile does not help: it governs caching and reordering by the compiler, not the atomicity of the machine's stores. Fix one: store only the low 32 bits, which is a single naturally aligned store and therefore atomic, and accept the 71.6-minute wrap (fine, because the value is consumed milliseconds later). Fix two: wrap both the write and the read in a critical section with the same spinlock — portENTER_CRITICAL_ISR() in the handler, portENTER_CRITICAL() in the task. A third option is to pass the timestamp through a queue, which copies it under the queue's own protection.

    3A tag runs perfectly on the bench for days. In the field a small number of units panic with a message about the cache. The handler is a correct six-microsecond queue send. What is the mechanism, and why did the bench never show it?›

    The handler lives in flash. Whenever the firmware writes flash — an NVS commit of the sequence number, an OTA chunk — the instruction cache is disabled for the duration. An interrupt arriving inside that window makes the core fetch the handler from an address it cannot read, and the panic names the cache rather than the handler. The bench never showed it because the bench tag was not being moved: the probability of an edge landing inside a few milliseconds of flash write is proportional to the motion event rate, so it appears only on deployed, handled assets. The fix is IRAM_ATTR on the handler, ESP_INTR_FLAG_IRAM when installing the ISR service, and checking that every function the handler calls is also in IRAM — a queue send from ISR is, a logging call is not.

    4Beacon polls the SHT40 but interrupts on the accelerometer. Both are sensors on the same I2C bus. Justify the asymmetry with numbers.›

    The SHT40's readiness is not an event, it is a constant: the datasheet specifies the high-precision conversion time (8.2 ms maximum), so the firmware starts a one-shot timer for 8.5 ms and reads. There is nothing to be told, no interrupt pin on the part, and no variance to absorb. Motion is the opposite: rare, asynchronous, and the entire reason the device may skip its 60-second sleep. Polling it would mean waking at the accelerometer's 25 Hz rate — every 40 ms — where each wake costs a large fraction of the canon's 45 ms active window at 40 mA; even a conservative tenth of that averages about 4.5 mA, which empties a 1000 mAh cell in roughly nine days against R1's six-month requirement. Sleeping with an interrupt armed costs 8 µA. The rule generalises: poll what is scheduled, interrupt what is rare, and never interrupt on something you could have computed from a datasheet number.

    Next: three buses, three philosophies →