Skip to content
Tech Interview Prep

Top 100 Embedded Software Engineer Interview Questions and Answers

The questions most likely to come up in your Embedded Software Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.

Curated: · Written: · Reviewed: —

Reviewed 0Review pending 100

100 questions · Flow follows Relevance until this set has a learning order.

Q&A-1When do you need volatile on a memory-mapped register, and what does it still not guarantee about atomicity or ordering?

The 90-second answer

Use volatile when the compiler must not cache, merge, or drop an access because something outside the current thread of execution can change the value: hardware behind a memory-mapped register, an ISR, or a DMA engine. On a Cortex-M UART status register, for example, the TXE bit changes without any C code writing it. Without volatile, the compiler is entitled to load the register once and test that cached value forever.

volatile does not make an access atomic and it does not provide the ordering guarantees of a memory barrier. A read-modify-write such as reg |= BIT is still load, modify, store. If an ISR or another core writes the same register between the load and the store, an update is lost. It also does not flush caches, order DMA against CPU writes, or make a multi-byte value safe to read while it is being updated.

What volatile actually does

In C and C++, every access through a volatile lvalue is an observable access. The compiler must emit a load or store of the stated width each time the abstract machine says so, and it must not reorder volatile accesses relative to each other. It may still reorder non-volatile accesses around them, and the hardware may still reorder the resulting bus transactions unless you add barriers.

C
/* STM32-style UART, C11, GCC/Clang for Cortex-M */
#define UART_SR  (*(volatile uint32_t *)0x40011000u)
#define UART_DR  (*(volatile uint32_t *)0x40011004u)
#define TXE      (1u << 7)

void uart_putc(char c)
{
    while ((UART_SR & TXE) == 0u) { /* must re-read hardware */ }
    UART_DR = (uint32_t)(uint8_t)c;
}

Drop volatile from UART_SR and an optimising compiler can legally turn the loop into a single test of a register value loaded before the loop. The program then hangs at -O2 while working at -O0. That is the classic symptom: it works unoptimised because the compiler happened to reload, and breaks once it stops.

Situationvolatile aloneWhat else is needed
---------
---------
---------
Poll a hardware status bitYesNothing, if the register is single-copy and the width matches the bus
Flag set in ISR, read in mainYes for visibility to the compilerAtomicity if the value is wider than the bus or read-modify-written
Counter incremented in ISR, read in mainNo, not by itself_Atomic uint32_t, or a critical section disabling interrupts around the read
Buffer filled by DMA, CPU reads itNoCache invalidate for the buffer range, then a barrier before reading the completion flag
CPU writes buffer, then rings a doorbell registerNoCache clean, then __DMB() before the doorbell store so data reaches memory first

Where it falls short: a worked failure

C
volatile uint32_t rx_count; /* incremented in the UART ISR */

uint32_t snapshot(void)
{
    return rx_count; /* one 32-bit load on Cortex-M3/M4 */
}

On a 32-bit Cortex-M with an aligned uint32_t, that load is a single LDR and will not tear. That is a property of the target and the alignment, not of volatile. Move the same code to a 16-bit core, an unaligned access, or a 64-bit counter and the ISR can fire between the two halves of the load, producing a value that never existed. The fix is to state the requirement explicitly:

C
#include <stdatomic.h>
_Atomic uint32_t rx_count; /* ISR: atomic_fetch_add_explicit(&rx_count, 1, memory_order_relaxed); */

uint32_t snapshot(void)
{
    return atomic_load_explicit(&rx_count, memory_order_relaxed);
}

The same gap appears with read-modify-write on a shared register. UART_CR1 |= USART_CR1_UE compiles to load, OR, store. If the ISR clears a different bit in UART_CR1 in between, the ISR update is overwritten. Use a hardware set/clear register if the peripheral provides one, mask interrupts around the sequence, or move ownership of the register to one context only.

Ordering and DMA

volatile orders volatile accesses against each other at the compiler level. It does not order a normal memory write against a later volatile doorbell write, and it does not order anything at the hardware level on a multicore or cached part. For DMA the sequence that matters is: write the buffer, clean its cache lines to memory, issue __DMB(), then write the doorbell. On completion, invalidate the buffer lines before the CPU reads them, with a barrier after the flag read. Skipping the cache maintenance is the usual cause of "DMA wrote garbage" or "CPU read stale data", and no amount of volatile on the pointer fixes it.

Rule of thumb I use in review: volatile on every memory-mapped register access, _Atomic or a critical section for anything shared between ISR and main that is wider than a single aligned bus access or read-modify-written, and explicit cache maintenance plus barriers around DMA. If a reviewer asks why a plain volatile flag is enough for a single status bit, the answer is the single aligned load. If the value is a counter, a struct, or a buffer, it is not.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-2Before the CPU reads a buffer that DMA just wrote on a cache-enabled Cortex-M, what cache operation must it do and why?

The 90-second answer

Invalidate the cache lines covering the buffer before the CPU reads it. DMA writes directly to RAM and does not update the CPU data cache. If the CPU cached that address earlier, a normal load will hit the old cached line and return stale data. Invalidation discards the cached copy, so the next load fetches the bytes DMA just wrote.

The opposite direction uses clean. When the CPU writes a transmit buffer and DMA will read it, clean the lines first so the dirty data is pushed to RAM before DMA starts.

Why the stale read happens

On Cortex-M7 parts such as the STM32H7, the data cache line is typically 32 bytes. The CPU caches whole lines, not single bytes. Once a line is cached and marked clean, loads are served from the cache until the line is evicted or invalidated.

StepActorResult
1CPU reads rx_buf[0]Line containing rx_buf is cached from RAM
2DMA writes new frame to rx_buf in RAMCache line is unchanged and now holds older data
3CPU reads rx_buf[0] againCache hit, CPU gets the old frame
4CPU invalidates the line, then reads againCache miss, CPU fetches the new frame from RAM

Invalidation is safe for a receive buffer because the cached copy is older than RAM. Discarding it loses nothing. Cleaning that same buffer would be wrong, because clean writes the cached copy back to RAM and can overwrite the DMA data.

C
#include "core_cm7.h"

#define CACHE_LINE 32U

__attribute__((aligned(CACHE_LINE)))
static uint8_t rx_buf[256];

/* In the DMA transfer-complete interrupt, before the CPU reads rx_buf */
void rx_ready(void)
{
    SCB_InvalidateDCache_by_Addr((uint32_t *)rx_buf, sizeof(rx_buf));
    __DSB();
    __ISB();
    /* rx_buf can now be read safely */
}

CMSIS rounds the address down and the size up to whole cache lines. __DSB() waits for the invalidation to finish and __ISB() prevents the pipeline from fetching ahead with the old line still present.

DMA writes buffer in RAM Transfer complete Invalidate cache lines CPU reads buffer Cache miss fetches new data

The one alignment trap worth knowing

Align DMA buffers to the cache line size and keep other variables out of the same line. Invalidation discards the whole line. If a neighbouring variable shares that line and is dirty, meaning the CPU wrote it and it has not reached RAM yet, invalidation will discard that write. A dedicated aligned buffer, or a separate linker section for DMA buffers, avoids the problem. Marking the buffer non-cacheable in the MPU is another option, and it removes the maintenance step at the cost of slower CPU access to that memory.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-3On a 16 KB RAM MCU, a 3 KB UART DMA buffer must coexist with two RTOS task stacks, a separate ISR stack, and a heap placed by the linker next to .bss: how do you allocate it and prove neither stack growth nor DMA will corrupt it?

The 90-second answer

Place the 3 KB buffer in a named linker section inside SRAM, reserve the stack regions explicitly in the linker script, and keep it out of both the heap and every task stack. Static placement alone does not solve this part. The default linker script lets .bss grow upward from the bottom of SRAM while the main stack grows downward from the top, with the heap in between. Nothing checks the gap. A 3 KB buffer in .bss shrinks that gap by 3 KB and the first sign of trouble is a corrupted variable, because most Cortex-M0 and M4 parts in this class have no MPU to fault on the collision. The fix is a linker script that gives each region a hard limit, plus a DMA alignment check against the controller's boundary rule.

Assume 16 KB SRAM, Cortex-M4 at 120 MHz, UART DMA at 115200 baud, two FreeRTOS tasks, and interrupts using MSP while tasks use PSP. That split matters. The ISR stack is separate, so a buffer on a task stack and a buffer on the ISR stack fail in different places.

C
/* rx_dma.c, GCC 12.2, Cortex-M4, -O2 */
#include <stdint.h>
#include <stddef.h>

#define RX_SIZE 3072u

/* Named section so the map file and linker script can bound it.
   aligned(4) satisfies most DMA channels; check the reference
   manual for a 1 KB or 4 KB boundary rule on this part. */
__attribute__((section(".ram_rx"), aligned(4), used))
static uint8_t rx_buf[RX_SIZE];

volatile uint16_t rx_len;      /* set by DMA complete ISR */
volatile uint8_t  rx_ready;    /* 1 when a full frame is waiting */

uint8_t *rx_buffer(void) { return rx_buf; }
size_t   rx_capacity(void) { return RX_SIZE; }

Linker script, the part candidates usually skip:

LD
MEMORY {
  SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 16K
}
SECTIONS {
  .bss : { *(.bss) *(.bss.*) } > SRAM
  .ram_rx : {
    . = ALIGN(4);
    *(.ram_rx)
  } > SRAM
  .heap : { *(.heap) } > SRAM
  /* Stacks reserved at the top, growing down. ASSERT fails the
     build if .bss + .ram_rx + .heap ever reach this region. */
  .stack_isr : { . = ALIGN(8); *(.stack_isr) } > SRAM
  ASSERT(. <= ORIGIN(SRAM) + LENGTH(SRAM) - 1024, "SRAM overflow")
}

The ASSERT converts a runtime corruption into a build failure. Without it, ld happily overlaps the heap with the stack region and the map file still looks tidy.

RAM budget with real figures

RegionBytesHow bounded
.data + .bss (globals, TCBs, queues)4096Map file
.ram_rx buffer3072Section size, checked above
Heap (heap_4, small objects only)2048configTOTAL_HEAP_SIZE
Task stacks, 2 tasks20481024 each, watermark sized
ISR stack (MSP)1024Reserved, worst ISR nesting
Guard and alignment slack4096Deliberately unallocated
Total16384Guard absorbs growth before collision

The 4 KB guard is the senior decision. It looks wasteful on a 16 KB part and it is what buys diagnosis time. If a task stack grows past its watermark, it eats guard first and a canary check in the idle task fires before it reaches .ram_rx. Remove the guard to fit a second buffer and the failure becomes silent corruption of received frames.

Stack sizing, exact working

Fill each stack with 0xA5 at creation. Run the worst case: deepest call chain, longest ISR nesting, DMA complete ISR preempting the lowest priority task. Then scan from the stack base upward to find the lowest untouched byte. Suppose task 1 shows 380 bytes used of 1024. Keep 1024, add the measured 380 plus ISR frame overhead, and re-check after any new library call. A 3 KB local array would show 3072 bytes used and fail this test immediately, which is the proof the interviewer wants. The ISR stack needs the same treatment with all interrupt priorities enabled, because MSP usage is invisible to the RTOS stack checker.

DMA constraints that interact with placement

Three checks, in order. First, alignment and boundary: read the DMA channel section of the reference manual. Some controllers require word alignment, some forbid crossing a 1 KB boundary, and a 3072 byte buffer starting at an arbitrary .bss address can cross one. aligned(4) handles the first, the named section plus ALIGN(1024) at the section start handles the second if required. Second, lifetime: DMA writes asynchronously, so the CPU must not read the buffer until the transfer complete flag sets rx_ready. Third, re-arm: stop the channel, clear the flag, then restart. Re-arming while the previous transfer is still running is the subtle failure. It produces a frame whose first bytes are new and whose tail is old, and a checksum over the whole frame passes only by luck.

DMA complete ISR Stop channel Read count, set rx_ready Task processes frame Clear rx_ready Clear flag, re-arm DMA

Failure modes and detection

Stack into .bss collision: detected by canary and watermark, prevented by the linker ASSERT. Heap fragmentation: avoided by keeping the 3 KB buffer out of malloc entirely, since heap_4 on 2 KB cannot hold it anyway. DMA overrun past the buffer end: detected by a length check in the ISR, where a count equal to RX_SIZE means the frame was truncated and the next byte would have overwritten the heap. Each mode has a different signature, and naming them is what separates a candidate who has shipped this from one who has read about static allocation.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-4Your Cortex-M4 thread HardFaults on a bad pointer dereference and BFARVALID is set. How do you decode the stacked frame and BFAR to find the faulting instruction and address?

The 90-second answer

On Cortex-M4 the core pushes a basic exception frame onto the stack of the interrupted context when the fault is taken. That frame holds the program counter of the instruction that faulted. The System Control Space registers hold the cause. For a precise bus error I read the stacked PC to find the instruction, and BFAR to find the address it tried to access, but only after checking BFARVALID in CFSR. If BFARVALID is clear, BFAR is stale and I trust only the PC.

I assume the fault happened in thread mode, so the frame is on PSP. I capture it in the HardFault handler before doing anything else, because any function call in the handler will use the stack and shift what I need to read.

C
// Cortex-M4, ARMv7-M Architecture Reference Manual
typedef struct {
    uint32_t r0, r1, r2, r3, r12, lr, pc, psr;
} StackedFrame;

void HardFault_Handler(void)
{
    // Thread mode on Cortex-M4 uses PSP. Handler mode would use MSP.
    StackedFrame *f = (StackedFrame *)__get_PSP();

    uint32_t hfsr = SCB->HFSR;
    uint32_t cfsr = SCB->CFSR;  // MMFSR | BFSR | UFSR
    uint32_t bfar = SCB->BFAR;

    log_fault(f->pc, f->lr, hfsr, cfsr, bfar);
    while (1) { __DSB(); __ISB(); }
}

The handler logs and stops. It does not call printf, allocate memory, or touch the peripheral that faulted. Logging happens from the captured values, ideally over SWO, so a second fault in the handler does not overwrite the evidence.

Worked decode

Suppose the log shows this after a thread dereferences a bad pointer:

RegisterValueMeaning
Stacked PC0x08001234Faulting instruction. Disassemble this address in the ELF for the exact build.
Stacked LR0x08001238Return address, normally the next instruction.
Stacked xPSR0x01000000EPSR.T set. Thumb state, as expected on Cortex-M.
HFSR0x40000000FORCED set. A configurable fault escalated to HardFault.
CFSR0x00000082BFSR bits: PRECISERR (bit 1) and BFARVALID (bit 7).
BFAR0x20001004Address that faulted. Valid because BFARVALID is set.

That combination tells a precise story. PRECISERR means the core knows which instruction faulted, unlike an imprecise error where the PC can be several instructions past the cause. BFARVALID means BFAR holds the exact data address for that instruction. So I disassemble 0x08001234, confirm it is a load or store, and then ask why 0x20001004 was inaccessible. On a typical STM32F4 that address is in SRAM, so I would check for an uninitialised or freed pointer, a corrupted struct, or an MPU region that blocks access.

What to check before trusting BFAR

I read HFSR first. If FORCED is set, the real cause is in CFSR, not in HFSR itself. Then I look at the BFSR byte of CFSR. PRECISERR plus BFARVALID is the case where BFAR is trustworthy. If BFARVALID is clear, I ignore BFAR completely and work from the stacked PC alone, often with a breakpoint on the suspect address in a debug build.

Two practical traps come up often. Reading MSP when the fault was in thread mode gives a frame full of handler data, so the PC looks random. And reading the frame after the handler has already pushed registers gives the same problem. Capturing PSP in the first instructions, storing the values in a noinit buffer, and only then logging avoids both. This decode also assumes Cortex-M3/M4/M7. Cortex-M0/M0+ has no BFAR or CFSR in this form, so there the stacked PC is all you get.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-5A SysTick ISR increments a 32-bit tick counter while a task reads it. How can that read return a corrupted value, and how would you fix it?

The 90-second answer

A 32-bit counter is only atomic if the read is a single bus transaction. On a 16-bit MCU, or when the compiler splits a 32-bit load into two 16-bit loads, the ISR can fire between the halves. The task then assembles a value that never existed.

Assume tick is volatile uint32_t, incremented by SysTick at 1 kHz, and the task reads it on a 16-bit bus (or a compiler that emits LDRH pairs). The low half wraps every 65,536 ticks, about 65.5 seconds. That wrap is where the tear happens.

Steptick in memoryTask has readISR fires?
10x0000FFFFlow = 0xFFFFno
20x00010000low = 0xFFFFyes, increments
30x00010000high = 0x0001no
4assembled0x0001FFFFtask returns 131,071 instead of 65,536

The error is exactly 65,536 ticks. A monotonicity check in the task (now >= last) still passes, so the bug shows up as a sudden jump in elapsed time, a missed timeout, or a timestamp that goes backwards when the halves are read in the other order. It is rare, roughly once per wrap per read, which is why it survives testing and appears in the field.

Fixes, and what each costs

C
/* Checked against GCC 13 for ARM Cortex-M, -O2 */
volatile uint32_t tick_count;

void SysTick_Handler(void) { tick_count++; }

/* Option 1: critical section. Correct on any bus width. */
uint32_t read_tick_critical(void)
{
    uint32_t primask = __get_PRIMASK();
    __disable_irq();
    uint32_t v = tick_count;
    __set_PRIMASK(primask);
    return v;
}

/* Option 2: read twice, retry if it changed. No interrupt latency cost. */
uint32_t read_tick_retry(void)
{
    uint32_t a, b;
    do {
        a = tick_count;
        __DMB();              /* keep the two loads in order */
        b = tick_count;
    } while (a != b);
    return a;
}
ApproachGuaranteesCostWhen it is the wrong choice
Disable interrupts around the readAtomic on any bus, any compiler outputBlocks all interrupts for the duration, typically tens of ns for one load, but it also blocks higher priority ISRs and can add jitter if the section growsInside a tight loop, or where a 1 kHz SysTick must never be delayed
Read twice and retryDetects a tear without masking interruptsOne extra load in the common case, unbounded retries in theory, in practice one retry per wrapIf the counter changes faster than the task can read it, for example a free-running timer at MHz rates
C11 _Atomic uint32_t or atomic_load_explicitCompiler emits a single atomic access or a lock sequence, and the memory model is explicitDepends on the target, may call a library routine on 8-bit partsWhen the toolchain silently lowers it to a critical section you did not budget for
Hardware capture registerTimer peripheral latches the count on a trigger, task reads the latchNeeds a timer with capture or a DMA channel, board wiringWhen no spare timer channel exists

Two details candidates get asked about. First, volatile alone does not fix this. It stops the compiler caching tick_count in a register or deleting the second load in the retry loop, but it says nothing about tearing or ordering across the two halves. Second, on a 32-bit Cortex-M with an aligned uint32_t, a single LDR is atomic against the ISR, so the tear needs a wider counter, an unaligned access, or a compiler that splits the load. The retry loop still works there, because an increment between the two loads forces a retry, and the critical section works everywhere.

The failure mode to name in an interview is the silent one. No fault fires, no assert trips, and the returned value is plausible. Detection in production is a monotonicity and delta check in the consumer: if now - last exceeds the maximum plausible interval between reads, log the raw halves and the tick value at the time. That log is what turns a once-a-minute glitch into a reproducible trace.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-6What does priority inheritance do when a high-priority task blocks on a mutex held by a low-priority task?

The 90-second answer

Priority inheritance temporarily raises the priority of a low-priority task that holds a mutex, so it matches the priority of the high-priority task waiting for that mutex. The holder then runs ahead of medium-priority tasks and releases the mutex quickly.

Without it, priority inversion happens in three steps. Low locks the mutex. Medium becomes ready and preempts Low. High becomes ready and blocks on the mutex. The scheduler runs Medium, because Low is still the only task that can release the mutex, and High waits behind a task it outranks.

With inheritance, the kernel boosts Low to High's priority at the moment High blocks. Medium can no longer preempt Low. Low finishes its critical section, releases the mutex, and drops back to its own priority. High then acquires the mutex.

StepEventRunning taskHigh blocked
1Low locks mutexLowNo
2Medium becomes readyMediumNo
3High blocks on mutexMedium, or Low if boostedYes
4Low releases mutexHighNo
C
// FreeRTOS: a mutex provides priority inheritance.
SemaphoreHandle_t m = xSemaphoreCreateMutex();

// Low-priority task
xSemaphoreTake(m, portMAX_DELAY);
write_shared_buffer();
xSemaphoreGive(m);  // priority restored on release

// High-priority task
xSemaphoreTake(m, portMAX_DELAY);  // blocks, Low is boosted to this priority
read_shared_buffer();
xSemaphoreGive(m);
Low holds mutex High blocks on mutex Low boosted to High priority Low releases mutex High runs

The detail that trips people up in code is the choice of primitive. In FreeRTOS, xSemaphoreCreateMutex() gives inheritance. xSemaphoreCreateBinary() does not, even though both can be used as a lock of count one. Guarding a shared resource with a binary semaphore removes the boost, and the inversion comes back.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-7How do you size a task stack for a FreeRTOS task on Cortex-M4 when its worst-case call chain, a 256-byte local buffer, and nested interrupts all compete for the same RAM?

The 90-second answer

On Cortex-M4 with FreeRTOS, size the task stack from the worst call path, not the average. Get per-function stack use from the compiler, add the frames that are live at the same time, add alignment and the RTOS context frame, then add margin. Size interrupt nesting separately. Thread mode runs on PSP, handler mode runs on MSP, so a nested ISR does not eat the task stack on this core. It eats the main stack. Conflating the two is how a task gets 1 KB that works in test and a main stack that overflows only when two interrupts nest during a DMA burst.

Assume GCC or Clang for Cortex-M4F, FreeRTOS 11, stack grows down, 8-byte alignment. State that up front, because the arithmetic changes on Cortex-M0, RISC-V, or a port that runs ISRs on the interrupted task stack.

Worst-case path, with real frames

Compile with -fstack-usage. It emits a .su file per object with bytes per function. Cross-check it against the map file for large locals, because a 256-byte array that the optimiser promotes or a printf family call will not be obvious from source alone.

Worked example, hypothetical but labelled as such. Task sensor_task calls process_frame, which calls parse_packet, which calls crc16 and memcpy:

Frame live at deepest pointBytesNotes
sensor_task entry16saved regs, return address
process_frame40locals, spilled regs
parse_packet288256-byte buffer rounded to 264, plus 24 bytes locals
crc1624called from parse_packet, so its frame adds
Subtotal368

Add the FreeRTOS context save area that sits on the task stack on Cortex-M (hardware frame of 8 words, 32 bytes, plus port-specific registers), alignment padding, and any library call on that path. memcpy on this toolchain is a leaf with a small frame, snprintf is not. If the path can reach snprintf, sscanf, or floating point formatting, remeasure. Those routinely add 500 bytes to 1 KB and invalidate the table above.

368 bytes plus 32 bytes context plus 25% margin for compiler variation, inlined functions that change between builds, and a call you missed, gives about 500 bytes. Round up to the RTOS allocation granularity and to 512 bytes. Then prove it, do not trust it.

C
/* Fill pattern check, FreeRTOS on Cortex-M */
for (uint32_t i = 0; i < STACK_WORDS; i++) {
    task_stack[i] = 0xA5A5A5A5UL;
}
/* After the task has run its worst input for a soak period: */
UBaseType_t free_words = uxTaskGetStackHighWaterMark(NULL);
/* free_words * 4 = bytes never touched. Want at least 20% free. */

If the high water mark shows under 20% free, or the 0xA5 pattern is overwritten near the TCB, the estimate missed a path. Common misses: an error handler that logs with formatting, a recursive descent parser, and a local array in a function called only on malformed input, which is exactly the input you did not test.

ISR nesting goes on MSP, not PSP

Thread mode, PSP: task stack Exception entry: hardware pushes 32 bytes to MSP Handler mode, MSP: ISR locals and FromISR calls Nested higher priority ISR: another 32 bytes plus its frame on MSP Return: tail chaining may reuse the frame

Each exception entry on Cortex-M pushes xPSR, PC, LR, R12, R3 to R0, 32 bytes, onto MSP. Each ISR level then adds its own locals and any non-leaf calls. Size MSP for the deepest legal nesting: sum over priority levels that can preempt each other of 32 bytes plus worst ISR frame, plus the FreeRTOS portYIELD_FROM_ISR path if a FromISR call can trigger a context switch. Tail chaining helps when interrupts arrive back to back, it does not help when a high priority ISR preempts a low priority one mid execution.

Two traps follow from this split. First, an ISR that calls a regular task function, or a driver that shares code between ISR and task context, can put ISR frames on the wrong stack in some ports and designs. Keep ISR code leaf-like, use FromISR variants, and never block. Second, if you disable interrupts around a critical section and a DMA ISR fires the moment you re-enable, the nesting depth at that instant is the worst case, not the typical one.

When not to use this method

Static .su sums fail with recursion, variable length arrays, alloca, and function pointers where the call graph is not closed. For those, bound the recursion depth in code, ban VLAs on the task path, and measure with the fill pattern under fault injection. If RAM is tight enough that 512 bytes matters, move the 256-byte buffer to a static or heap allocation with a fixed lifetime, and accept the loss of reentrancy. That trade is usually cheaper than discovering the overflow in the field, where it presents as a HardFault with a corrupted stack and no BFAR pointing at your task.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-8Three tasks need the same I2C bus for sensor reads and EEPROM writes. How do you choose between a mutex, binary semaphore, counting semaphore and queue to protect it?

The 90-second answer

Use a mutex for the bus itself. The bus is a single, owned resource: one transaction at a time, from START to STOP, with no interleaving. A mutex gives you ownership, which a semaphore does not, and on FreeRTOS and most RTOS ports it also gives you priority inheritance. That matters here. If a low priority task holds the bus while a high priority task waits, inheritance temporarily raises the holder so a medium priority task cannot starve it indefinitely.

A binary semaphore looks similar because it also has a count of one, but it has no owner. Any task can give it, including one that never took it, and the kernel cannot apply inheritance to a holder it cannot identify. A counting semaphore is for a pool of N identical things, such as four DMA buffers. The I2C bus has N equal to one, so a count above one would actively permit the corruption you are trying to prevent. A queue is different in kind: it transfers data or work, it does not by itself stop two tasks from driving the pins at once.

The exception is architecture. If you put a single bus manager task in charge and every other task posts a transaction descriptor to a queue, the queue plus that one consumer provides exclusion without any task ever blocking on a mutex. That is often the cleaner design when transactions are produced from interrupt context or when you want backpressure to be explicit.

What each primitive actually does

PrimitiveOwnershipPriority inheritanceCorrect use on I2C
MutexYes, taker must giveYes on FreeRTOS, ThreadX, ZephyrGuard the bus around one full transaction
Binary semaphoreNoNoSignal an event, for example transfer complete from an ISR
Counting semaphoreNoNoPool of identical resources, for example 4 buffers
QueueTransfers itemsNo, unless the consumer is the sole bus userHand transaction requests to one bus manager task

The mutex case in C, checked against FreeRTOS 11:

C
static SemaphoreHandle_t i2c_mutex;

bool i2c_transfer(i2c_device_t *dev, uint8_t *buf, size_t len)
{
    if (xSemaphoreTake(i2c_mutex, pdMS_TO_TICKS(50)) != pdTRUE) {
        return false; /* bus busy or holder wedged, do not drive pins */
    }
    bool ok = hal_i2c_write_read(dev->addr, buf, len, 1000); /* 1 ms timeout */
    xSemaphoreGive(i2c_mutex);
    return ok;
}

Hold the mutex for the whole transaction, not per byte. At 100 kHz, a 16 byte read with register address and repeated START takes roughly 1.6 ms on the wire. Releasing between bytes lets another task issue its own START in the middle and the slave sees a framing error. The 50 ms take timeout is a policy choice: long enough to cover a few queued transactions, short enough that a sensor task with a 100 ms period can log the failure and retry instead of missing its deadline silently.

The queue alternative removes the mutex entirely:

C
typedef struct { uint8_t addr; uint8_t *buf; size_t len; SemaphoreHandle_t done; } i2c_job_t;

/* Producers: xQueueSend(job_queue, &job, 0);  Bus manager task: sole caller of hal_i2c_* */

Here the queue length is your backpressure. A queue of 8 jobs at 1.6 ms each bounds worst case wait to about 13 ms, and a full queue fails the producer immediately rather than blocking it. The cost is latency and complexity: every job needs a completion signal, and a producer that needs the read data must block on that signal anyway.

Yes No, tasks call driver directly Yes No Multiple tasks need the bus Can one bus manager task own it? Queue of transaction jobs Mutex around full transaction Called from ISR? Never take mutex in ISR. Post to queue or set flag

Failure modes to name

Deadlock and priority inversion are the classic pair. Priority inversion is fixed by the mutex, not by raising task priorities by hand. Deadlock still happens if code takes the I2C mutex and then waits on a queue or another mutex while holding it, or if an ISR tries to take it. FreeRTOS mutex take from an ISR is not permitted, so ISR producers must use xQueueSendFromISR or a binary semaphore given from the ISR to wake a task.

A wedged bus is the hardware failure. If a slave holds SDA low, the next START fails and every task queues behind the mutex. Detect it with the transfer timeout above, count consecutive failures, and on a threshold run bus recovery: reconfigure the pins as GPIO, clock SCL nine times, issue a STOP, then restore I2C mode. That recovery must also run under the mutex, or it races with a live transaction.

Choose the mutex when tasks share a driver directly and transactions are short. Choose the queue when you want one owner, bounded waiting, and ISR-safe submission. Do not use a counting semaphore for the bus, and do not use a binary semaphore as a mutex substitute unless you can prove no priority inversion and no stray give can occur, which on a shared bus you usually cannot.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-9For a UART ISR producing bytes and a task consuming them, compare a mutex-protected buffer with a single-producer single-consumer ring buffer. Which would you use and how do head and tail indices work?

The 90-second answer

I would use the single-producer single-consumer ring. A mutex looks simpler, but it fits badly when one side is an ISR. If the task holds the mutex while the UART interrupt fires, the ISR either blocks, which an ISR must never do, or it tries to take a mutex from interrupt context, which most RTOS ports forbid. Even with priority inheritance, the ISR now waits on task scheduling. That adds unbounded latency to byte reception and risks overrun at the UART hardware.

The ring avoids the lock by giving each index exactly one writer. The ISR only writes the head index and the buffer slots. The task only writes the tail index. Neither side writes the other's index, so there is no read-modify-write race to protect.

C
// C11, Cortex-M4, GCC 12. Buffer size must be a power of two.
#include <stdatomic.h>
#include <stdint.h>

#define RB_SIZE 256u
#define RB_MASK (RB_SIZE - 1u)

typedef struct {
    uint8_t buf[RB_SIZE];
    atomic_uint head; /* write index, ISR only */
    atomic_uint tail; /* read index, task only */
    atomic_uint dropped;
} ring_t;

void ring_push_isr(ring_t *r, uint8_t byte)
{
    unsigned h = atomic_load_explicit(&r->head, memory_order_relaxed);
    unsigned t = atomic_load_explicit(&r->tail, memory_order_acquire);
    if (h - t >= RB_SIZE) {
        atomic_fetch_add_explicit(&r->dropped, 1u, memory_order_relaxed);
        return;
    }
    r->buf[h & RB_MASK] = byte;
    atomic_store_explicit(&r->head, h + 1u, memory_order_release);
}

int ring_pop_task(ring_t *r, uint8_t *out)
{
    unsigned t = atomic_load_explicit(&r->tail, memory_order_relaxed);
    unsigned h = atomic_load_explicit(&r->head, memory_order_acquire);
    if (h == t) return 0;
    *out = r->buf[t & RB_MASK];
    atomic_store_explicit(&r->tail, t + 1u, memory_order_release);
    return 1;
}

Head and tail are monotonic counters, not pointers that reset at the end of the array. The slot is index & RB_MASK. The count in the buffer is head - tail in unsigned arithmetic, so the 32-bit counters can wrap and the difference still works. Empty is head == tail. Full is head - tail == RB_SIZE.

The ordering matters in a small way. The ISR writes the byte before it publishes the new head, so the store to head uses release ordering. The task reads head before it reads the byte, so that load uses acquire ordering. On Cortex-M the main risk is the compiler reordering these accesses, and the atomics prevent that.

Worked trace

StepheadtailIn bufferAction
1000Task finds buffer empty
2101ISR stores byte at slot 0, publishes head
3202ISR stores byte at slot 1, publishes head
4211Task reads slot 0, publishes tail
52560256Buffer full, next byte increments dropped

Overflow and waking the task

When full, the ISR drops the new byte and increments dropped. That keeps the ISR short and gives the task a counter to log. Silently overwriting old data would corrupt a frame without any trace of the loss. If the protocol can resynchronise, dropping the oldest byte is also defensible, but the consumer then needs to know a gap happened.

The ISR gives a binary semaphore or task notification after a push. The task wakes, drains the ring until empty, then blocks again. At 115200 baud, 8N1, a byte arrives about every 87 microseconds, so 256 bytes covers roughly 22 ms of task delay. That figure is the check that the buffer size matches the worst-case task latency.

The mutex version remains the right choice if a second producer appears, for example a DMA callback also writing bytes. At that point the single-writer assumption is gone and the design needs a lock or an atomic compare-and-swap loop on head.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-10A bug only happens on hardware, never in simulation. What is the first probe you would add, and what would you expect it to show?

The 90-second answer

I would toggle a GPIO at the entry and exit of the suspect code and capture it on a logic analyzer. Simulation runs with ideal, deterministic timing. Hardware has a real clock, real peripheral settling times and real interrupt latency. A GPIO pulse shows the actual duration and ordering on the board, which is the first thing simulation cannot show me.

I pick one suspect function, for example a sensor read or a DMA start, and bracket it with two toggles. If the pulse width on hardware is longer, shorter or jittery compared with the expected period, timing is the cause. If the pulse is correct alone but overlaps another pulse when a second channel runs, I have a race. Either result narrows the next probe. Without that measurement I would be guessing from code that already looks correct in simulation.

C
/* GCC for Arm, Cortex-M4. GPIOA pin 5 is a debug output. */
static inline void probe_set(void)   { GPIOA->BSRR = (1u << 5); }
static inline void probe_clear(void) { GPIOA->BSRR = (1u << (5 + 16)); }

void sensor_read(void)
{
    probe_set();
    i2c_transfer(sensor_addr, rx_buf, sizeof(rx_buf));
    probe_clear();
}

The analyzer gives me three numbers per run: pulse width, gap to the next pulse, and variation across runs. I record them for ten runs and compare them with the datasheet timing for the peripheral.

What the analyzer showsWhat it points toNext check
Pulse wider than the datasheet transfer timeClock stretch, bus contention or a slower real clockMeasure the I2C clock line and the MCU clock
Pulse width varies run to runInterrupt preemption or DMA contentionAdd a second pin toggled in the ISR and compare ordering
Pulse correct, bug still occurs inside itThe fault is not duration but state, such as uninitialized memoryFill RAM with 0xA5 in a debug build and watch for a HardFault
Pulse missing on some runsCode path not reached, or power droop resets the partScope the supply rail during the operation
No Yes Bug on hardware only Toggle GPIO around suspect code Capture with logic analyzer Pulse matches expected timing? Timing or race on real hardware Look at memory or power next

A GPIO toggle costs a few cycles and does not stall the CPU the way a breakpoint or a UART print does. A breakpoint halts the core, lets a watchdog expire and can make a timing bug vanish. A 200 byte print over 115200 baud UART takes about 17 ms, which can serialize a race that normally overlaps. The toggle avoids both problems and leaves evidence I can defend: a measured width in microseconds, not an impression that the code felt slow. If the width is wrong, I fix the cause, such as polling a ready flag instead of assuming a fixed delay, and I rerun the same capture to confirm the pulse now matches the datasheet.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-11Given only a peripheral's SPI timing diagram, how do you determine CPOL and CPHA, and what breaks if you get the phase wrong?

The 90-second answer

CPOL is the SCLK level with no transfer in progress, usually the level while CS is inactive. CPHA decides whether the first SCLK edge samples data or shifts it. Read those two facts off the diagram in that order and the mode falls out, no trial and error.

ModeCPOLCPHASCLK idleSampled on
000lowrising, first edge
101lowfalling, second edge
210highfalling, first edge
311highrising, second edge

If MOSI already carries the first valid bit before the first edge, the peripheral samples on that first edge and CPHA is 0. If MOSI changes on the first edge and the first bit is only valid after it, the peripheral samples on the second edge and CPHA is 1. That single observation, data valid before edge one or after it, settles phase.

Reading a real diagram

Start at the left edge, before the first clock. Note CS going active and the SCLK level that sits there for the CS setup time. That is CPOL, even if the diagram draws the first pulse going the other way. Some vendors draw CPOL=1 parts with SCLK high at reset, others start the trace low and pulse high first. The idle level, not the first pulse direction alone, is the definition.

Then find the first MOSI transition. In a CPHA=0 diagram MOSI changes on the trailing edge, the edge that does not sample, so the first bit is stable through the leading edge. In a CPHA=1 diagram MOSI changes on the leading edge itself, and the receiver captures it on the next, trailing, edge. Mark the sampling edge with an arrow on the diagram. If you cannot tell which edge the vendor intends, look for the setup and hold annotations around MOSI. They are drawn around the sampling edge.

Two traps catch people here. First, vendor terminology. A few datasheets call the first edge "leading" regardless of CPOL, others define leading as the edge that leaves idle. Ignore the word and use the absolute edge, rising or falling, plus idle level. Second, dummy and turnaround bits. Flash parts in quad mode, some ADCs and displays insert dummy clocks after a command. Those clocks still obey the same CPOL and CPHA. Count them as clocks, do not let them make you think the first data bit is the first clock.

What a wrong phase actually does

Wrong CPHA shifts the whole stream by one bit. The receiver misses the first bit and captures one extra bit at the end, usually the first bit of the next byte or a zero from an idle MOSI line. The bus still clocks, CS still frames, and at low speed nothing looks electrically wrong. The decoded values are just wrong in a consistent way.

Worked example, hypothetical but typical. Master sends 0xA5 (10100101, MSB first) to a mode 0 peripheral, but is configured for mode 1:

Bit positionSentSampled by peripheral (mode 0)Sampled by master in mode 1
111next bit, 0
2001
3110
4001
5000
6111
7000
8110
9idle MOSI, say 0not sampled1, the last sent bit

The master reads back 01010010 (0x52) instead of 0xA5. A read ID command of 0x9F becomes 0x4F plus a stray bit, which looks like a dead part rather than a mode error. Wrong CPOL is harsher. The first edge is then the wrong direction, so the peripheral may sample a transition, miss the first clock entirely, or interpret the idle level as a clock when CS asserts. Symptoms are usually a completely unresponsive device or a command that only works when you toggle CS manually.

Configuring and verifying

On STM32 HAL the mapping is direct, and the same fields exist under different names on most MCUs:

C
hspi.Init.Mode = SPI_MODE_MASTER;
hspi.Init.CPOL = SPI_CPOL_LOW;      /* SCLK low at idle: mode 0 or 1 */
hspi.Init.CPHA = SPI_CPHA_1EDGE;    /* sample on first edge: mode 0 */
hspi.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
/* Keep SCLK under the peripheral maximum, e.g. 20 MHz for a 80 MHz
   peripheral clock with prescaler 4, and check the datasheet table
   for read versus write limits, they often differ. */

Verify with a logic analyser before debugging the driver. Decode with the mode you derived, check that the first decoded byte matches the command in the datasheet, and confirm MOSI setup time to the sampling edge and hold time after it. If the first byte is shifted by one, flip CPHA only. If the device ignores everything, check CPOL and CS polarity first. Then check the constraints the mode does not cover: maximum SCLK, CS setup and hold, inter-byte gap, and whether the part requires mode 0 or 3 only, as many SPI flash devices do, with the other mode reserved for a different protocol variant.

A final check worth doing on the bench: scope SCLK idle with CS deasserted. If your firmware leaves it high while the datasheet shows low idle, CPOL is wrong even if a transfer happens to decode, and the first edge after CS asserts will be a spurious clock on some peripherals.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-12A sensor holds SCL low for 30 ms after the address ACK while it converts. How does clock stretching work, and how do you tell it apart from a stuck bus?

The 90-second answer

Assume a controller at 100 kHz, so one SCL period is 10 us, talking to a sensor that needs 30 ms to convert. After the address ACK the sensor pulls SCL low and holds it until conversion finishes. That is clock stretching, and the controller must wait. It is not an error, and it is not a stuck bus, until a timeout you set from the datasheet expires.

Stretching works because I2C is open drain. The controller drives SCL low to start a clock and releases it to end the low phase. The target can then pull SCL low again before the controller drives it high. The controller samples SCL after releasing it. If SCL is still low, the target is stretching and the controller waits. No clock edge has happened, so the byte in progress has not advanced.

A stuck bus looks similar on a scope but differs in SDA. During stretching SDA is released or driven by the target as part of the current byte. When the bus is stuck after a reset, SDA stays low while SCL is high and the bus should be idle. That means the target thinks it is still sending a byte and is waiting for clocks that will never come.

Condition on the wireMeaningDriver action
SCL low after controller releases it, SDA not stuck low at idleStretchingWait until SCL goes high or timeout expires
SDA high on the ninth clock of the address phaseAddress NACKSend STOP, check address and power, retry a limited number of times
SDA high on the ninth clock of a data byteData NACKSend STOP, do not advance the buffer, log the register
SDA low while SCL high and no transfer activeTarget stuck mid-byteClock out up to nine SCL pulses, send STOP, reinit

Choosing the timeout

I2C defines no stretch limit. SMBus 2.0 defines 25 ms, which is why some parts stay under it and others do not. For a 30 ms conversion, set the per-byte timeout above the worst case in the datasheet, for example 50 ms, and keep a separate shorter timeout for the whole transaction if the application cannot tolerate a long block. A 5 ms timeout here would fail every conversion, even though the sensor is healthy.

Poll SCL with a timer, not a loop count, so the timeout survives a clock change:

C
// C11, bare-metal controller at 100 kHz
static int wait_scl_high(uint32_t timeout_ms)
{
    uint32_t start = timer_ms();
    gpio_release_scl();
    while (gpio_read_scl() == 0) {
        if ((uint32_t)(timer_ms() - start) > timeout_ms) {
            return -1; /* stretch timeout, issue STOP and retry from start */
        }
    }
    return 0;
}

At 100 kHz, 30 ms of stretching equals about 3,000 normal clock periods. That arithmetic is why a timeout based on counting clocks, such as 100 clocks, would be wrong by a factor of 30.

Recovery when SDA is stuck

If the timeout expires and SDA is low at idle, clock the target out. Drive SCL with nine pulses at bus speed, then generate a STOP by pulling SDA low while SCL is high and releasing it. Nine pulses cover a partial byte plus its ACK clock. At 100 kHz that takes about 90 us.

C
static int bus_recover(void)
{
    gpio_open_drain_scl_sda();
    gpio_release_sda();
    for (int i = 0; i < 9 && gpio_read_sda() == 0; i++) {
        gpio_drive_scl_low();
        delay_us(5);
        gpio_release_scl();
        delay_us(5);
    }
    gpio_drive_sda_low();
    delay_us(5);
    gpio_release_sda();
    i2c_peripheral_reinit();
    return gpio_read_sda() ? 0 : -1;
}

If SDA is still low after that, the cause is usually a reset fault or a short, not a byte in progress. The next step is to reset or power-cycle the sensor. Retrying recovery in a tight loop will not release a shorted line.

Yes No Yes No SCL low after release SCL high within 50 ms? Continue current byte SDA low at idle? 9 clocks + STOP, reinit STOP, retry transaction

The distinction to defend in the interview is simple. Stretching is SCL low with the transfer still valid. A stuck bus is SDA low with no transfer valid. The timeout separates the two, and the recovery sequence only runs for the second case.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-13Your UART is logging framing and overrun errors at 115200 baud on a Cortex-M4. How do you tell them apart, find the cause, and recover the link?

The 90-second answer

Framing, overrun and baud mismatch look similar in a log, garbage bytes and a stuck receiver, but they originate in different places. Framing error means the stop bit was sampled low, so the frame boundary is wrong. Overrun means a byte arrived while the previous byte still sat unread in the receive data register or FIFO. Baud mismatch is a common cause of framing error, because the receiver drifts relative to the transmitter and samples the stop bit in the wrong place.

I separate them by reading the status flags before reading the data register, then I fix the cause in order: clock and baud first, then interrupt latency and buffering, then resynchronisation. Clearing flags without fixing the cause just buys a few clean bytes.

What each flag actually means

Assume 8N1, 10 bits per frame including start and stop, receiver oversampling by 16 and sampling near the middle of each bit.

FlagSet whenByte usable?Typical cause
FE, framing errorStop bit sampled as 0No, discardBaud or clock mismatch, line glitch, transmitter stopped mid-frame
ORE, overrun errorNew byte completes before RDR is readPrevious byte may be readable, new byte lost on many partsISR or task too slow, FIFO full, DMA stalled
NE, noise errorMajority vote across oversamples disagreesOften noSignal integrity, ground bounce, marginal levels
PE, parity errorParity bit mismatch, if parity enabledDepends on protocolBaud mismatch, corrupted line

On STM32F4 the flags live in USART_SR: ORE bit 3, NE bit 2, FE bit 1, PE bit 0. For that family the reference manual specifies that ORE is cleared by a software sequence of reading SR followed by reading DR. I use only that sequence in the code below and check the manual for the exact part in use, because the clearing sequence is part specific and a wrong sequence leaves ORE set.

Why baud mismatch produces framing errors

At 115200 baud the bit time is 1 / 115200 = 8.68 us, and a 10-bit frame lasts 86.8 us. The receiver resynchronises on the start bit edge, then samples each subsequent bit near its centre. If the transmitter clock is 2% fast, by the stop bit the accumulated drift is about 0.02 x 9 bit times, roughly 0.18 of a bit time. That still passes. At 4% mismatch the drift is about 0.36 of a bit time and the stop sample can land in the next start bit, which reads as 0 and sets FE. The arithmetic bound for the centre sample to stay inside the stop bit is drift below 0.5 bit time, about 5.5% over 9 bit times, but real margin is smaller because start edge detection, sampling quantisation and clock jitter consume part of that budget. I therefore treat the calculation as a bound to check against, not as a guarantee.

A worked check I do on the bench: measure the actual bit time with a scope or logic analyser, not the nominal baud. For example, with a USART clock of 84 MHz, the ideal divisor for 115200 is 84,000,000 / 115200 = 729.17. Programming BRR to 729 gives an actual baud of 84,000,000 / 729 = 115,226, an error of about 0.02%. If the measured bit time disagrees with that, the clock tree is feeding the USART from a different divider than I assumed. On many Cortex-M parts USART1 sits on PCLK2 and USART2 on PCLK1, and a prescaler change for another peripheral silently moves the baud by a factor of two.

FE or NE ORE Yes No Error flag set Which flag? Measure bit time, check clock tree and baud divisor Check ISR latency, FIFO depth, DMA and task wake time Fix clock or baud, flush receiver Wait for idle line, resync on next start bit Errors persist? Probe signal integrity and peer settings Resume, count errors per flag

Diagnosis in code

The ISR has to capture the flags with the byte, because reading DR first destroys the evidence. This sketch is for a bare-metal STM32F4 style register interface.

C
void USART2_IRQHandler(void)
{
    uint32_t sr = USART2->SR; /* read SR first */
    if (sr & USART_SR_RXNE) {
        uint8_t byte = (uint8_t)USART2->DR; /* SR then DR clears ORE on F4 */
        if (sr & USART_SR_ORE) {
            overrun_count++; /* byte arrived too late, count it, do not trust stream */
        } else if (sr & (USART_SR_FE | USART_SR_NE | USART_SR_PE)) {
            error_count++;   /* discard byte, frame boundary is suspect */
        } else {
            ring_push(&rx_ring, byte);
        }
    }
}

Two details matter here. First, I count each flag separately. A burst of FE with no ORE points at clock or wiring. A burst of ORE with clean framing points at software latency. Second, after FE I discard the byte and often the following bytes until an idle gap, because once framing slips the receiver may interpret the middle of a byte as a start bit and produce a run of garbage.

Recovery

Recovery depends on which flag dominated. For FE, I stop trusting the stream, flush the receive FIFO if the part has one, reprogram the baud divisor from the measured peripheral clock, and wait for at least one idle bit time before the peer sends again. If the peer supports it, a short idle or break condition forces the receiver back to a known state. For ORE, flushing alone is not a fix. I check worst-case interrupt latency: a 256-byte DMA transfer or a critical section that masks interrupts for 200 us will overrun a 115200 baud receiver, since a byte arrives every 86.8 us. The fix is a deeper FIFO, DMA into a circular buffer with the ISR only handling errors, or raising the UART priority above the offending interrupt.

I also verify the peer. A USB to serial adapter at a nominal 115200 can be off by more than 1%, and a peer running from an internal RC oscillator can drift several percent over temperature. That combination can pass at room temperature and fail in the field, which is why I log the measured bit time and the error counters with temperature when I reproduce it.

What I would not do is clear the flags in a polling loop and carry on. That hides a clock problem until the link fails under load, and it hides an overrun problem until data loss shows up as a corrupted protocol frame several layers up.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-14What is the standard way to debounce a mechanical button interrupt without blocking the ISR?

The 90-second answer

Record the edge time in the ISR and return immediately. Confirm the press later, after a short settle window, in a task or timer callback.

A mechanical contact bounces for about 1 to 20 ms, producing several edges for one press. Calling a delay or waiting for the pin to settle inside the ISR blocks other interrupts for that whole period. Masking the interrupt for a fixed 50 ms also works, but it can swallow a genuine second press that arrives inside the masked period.

Timestamp debounce avoids both problems. The ISR stores the current tick when an edge arrives and sets a pending flag. Edges that arrive within the debounce window are ignored. After the window expires, the task reads the pin again. If it is still in the pressed state, the press is real and the handler runs. Bounce edges return to the idle level between edges, so they fail that second read.

C
/* Cortex-M, 1 ms SysTick tick, active-low button, falling-edge interrupt */
volatile uint32_t g_tick_ms;
volatile uint32_t g_last_edge_ms;
volatile bool g_pending;

#define DEBOUNCE_MS 25u

void EXTI0_IRQHandler(void)
{
    EXTI->PR = EXTI_PR_PR0; /* clear the pending bit */
    uint32_t now = g_tick_ms;
    if ((now - g_last_edge_ms) >= DEBOUNCE_MS) {
        g_last_edge_ms = now;
        g_pending = true;
    }
}

void button_task(void *arg)
{
    for (;;) {
        if (g_pending) {
            g_pending = false;
            vTaskDelay(pdMS_TO_TICKS(DEBOUNCE_MS));
            if (button_pressed()) {
                handle_press();
            }
        }
        vTaskDelay(pdMS_TO_TICKS(5));
    }
}

The ISR does a compare, two stores, and a flag set. That takes microseconds, so higher priority interrupts are not starved. The slow confirmation happens in the task, where blocking is harmless.

Worked trace

Hypothetical trace with a 25 ms window, press at 100 ms:

Time (ms)PinISR actionResult
100falling100 ms since last accepted edge, set pendingpress pending
103risinginside window, ignorednone
106fallinginside window, ignorednone
111risinginside window, ignorednone
125still lowtask re-reads pin after windowhandle_press() once

One press produces one callback.

Two details matter. First, use unsigned subtraction, (now - g_last_edge_ms), so the comparison stays correct when the 32-bit tick wraps after about 49 days. Second, size the window from a scope trace of the actual switch. Most tactile switches settle within 20 to 30 ms, and a window much longer than that will merge a fast double tap into a single press.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-15How do you configure DMA double buffering so a display frame or ADC sample block is never torn between old and new data?

The 90-second answer

Use two buffers of identical size. DMA fills or transmits one while the CPU works on the other, and the swap happens only on a hardware boundary, never when the CPU gets round to it. For an ADC stream that boundary is the DMA transfer-complete or half-transfer interrupt. For a display it is vertical blank, or the DMA transfer-complete for a line buffer. If you swap mid-frame or mid-block, the consumer sees half old data and half new data. That is tearing for a display and a torn sample block for an ADC.

On STM32F4 and many similar parts this is the DMA double-buffer mode. Set DBM in the DMA stream control register, clear CT to start on buffer 0, and let hardware toggle CT at each transfer complete. The ISR then knows the other buffer is stable and the buffer CT now points to is busy.

C
/* STM32F4, ADC1 on DMA2 Stream0, 1024 uint16_t samples per buffer */
#define N 1024
static uint16_t buf[2][N] __attribute__((aligned(4)));
volatile uint8_t ready_idx; /* buffer CPU may read */
volatile uint8_t ready;

void adc_dma_init(void) {
    DMA2->S[0].CR = 0;
    DMA2->S[0].PAR = (uint32_t)&ADC1->DR;
    DMA2->S[0].M0AR = (uint32_t)buf[0];
    DMA2->S[0].M1AR = (uint32_t)buf[1];
    DMA2->S[0].NDTR = N;
    DMA2->S[0].CR = DMA_SxCR_CIRC | DMA_SxCR_DBM | DMA_SxCR_MINC
                  | DMA_SxCR_PSIZE_0 | DMA_SxCR_MSIZE_0
                  | DMA_SxCR_TCIE | DMA_SxCR_HTIE | DMA_SxCR_EN;
}

void DMA2_Stream0_IRQHandler(void) {
    uint32_t flags = DMA2->LIFCR;
    if (flags & (DMA_LIFCR_TCIF0 | DMA_LIFCR_HTIF0)) {
        /* CT now names the buffer DMA is writing. The other one is done. */
        ready_idx = (DMA2->S[0].CR & DMA_SxCR_CT) ? 0 : 1;
        ready = 1;
    }
    DMA2->LIFCR = DMA_LIFCR_CTCIF0 | DMA_LIFCR_CHTIF0;
}

The consumer copies or processes buf[ready_idx], then clears ready. It never touches the buffer CT points to. If ready is still set when the next interrupt arrives, the consumer fell behind. Count that as an overrun and drop the older block rather than letting DMA lap it.

Sizing and timing

Pick N from the consumer deadline, not from what fits. At 1 MSPS with 16-bit samples, N=1024 gives 1.024 ms per buffer. A processing task that must finish in 800 us has headroom. N=4096 gives 4.096 ms, which halves interrupt rate but doubles worst-case latency and RAM. Two buffers cost 2N2 bytes, so 4 KB here for N=1024. On a cache-enabled part, align both buffers to the cache line size, 32 bytes on Cortex-M7, and clean or invalidate as appropriate before the CPU reads data DMA wrote. Without that, the CPU can read stale cache lines even though DMA wrote memory correctly.

For a display the same arithmetic applies per line or per frame. A 480 by 272 RGB565 frame is 261,120 bytes. Sending that from one framebuffer while rendering into it tears. Keep a front buffer that DMA or the display controller reads, render into a back buffer, and swap pointers only in the VBlank ISR after the last line has been read out. With SPI line buffers instead, fill line buffer B while DMA sends line buffer A, and swap on the DMA transfer-complete interrupt, which lands between lines if you trigger it from the line timer.

DMA writes buffer 0 Transfer complete interrupt CT toggles to buffer 1 CPU processes buffer 0 DMA writes buffer 1 Transfer complete interrupt CPU processes buffer 1

Worked trace

TimeDMA active bufferCPU readsEvent
0 ms0noneDMA starts
1.024 ms10TC interrupt, CT toggles
1.5 ms10, still processingSafe, buffer 0 no longer written
2.048 ms01TC interrupt, buffer 1 complete
2.6 ms01Safe
3.072 ms1none, overrun countedConsumer missed buffer 0 deadline

Failure modes that still bite

Swapping by writing M0AR or the framebuffer pointer from task context races with DMA. DMA may have already loaded the next address. Always swap through the hardware mechanism, DBM and CT, or at a VBlank where the display controller has stopped reading the old buffer. A second failure is processing in the ISR. That stretches the interrupt, delays the next swap, and on a display can push you past VBlank into the next frame. Do the swap and flag in the ISR, do the work in a task. A third is unequal buffers. If the two buffers differ in length, the second transfer truncates or overruns and the trace above stops holding. Keep N identical and assert it at compile time.

For ADC, also check the peripheral side. Double buffering in DMA does not fix ADC overrun if the data register is not read before the next conversion completes. Set the ADC to continuous conversion with DMA request on, and confirm the OVR flag in ADC1->SR stays clear at your sample rate under worst-case interrupt load, not just in a quiet bench test.

That gives you a stream with no torn blocks, a measurable overrun counter when the consumer cannot keep up, and a swap point tied to hardware timing instead of task scheduling.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-16On a Cortex-M4, how do you set NVIC priority grouping and interrupt priorities so a safety ISR always preempts a telemetry ISR, and what can break that guarantee?

The 90-second answer

On Cortex-M, preemption is decided by the preemption priority, not by the raw priority byte. I would put the NVIC in priority group 4, give the safety interrupt preemption priority 0 and telemetry a lower preemption priority such as 5, and enable both only after those settings are in place. Group 4 means all four priority bits on an STM32F4 are preemption bits and there are no subpriorities, so the comparison is unambiguous.

C
/* STM32F4, Cortex-M4, CMSIS/HAL. Call once, before enabling IRQs. */
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);

HAL_NVIC_SetPriority(SAFETY_IRQn,    0, 0); /* highest preemption priority */
HAL_NVIC_SetPriority(TELEMETRY_IRQn, 5, 0); /* can be preempted by safety */
HAL_NVIC_SetPriority(SysTick_IRQn,   15, 0); /* keep tick below both */

HAL_NVIC_EnableIRQ(SAFETY_IRQn);
HAL_NVIC_EnableIRQ(TELEMETRY_IRQn);

Lower number wins on Cortex-M. The value written to NVIC->IPR is left aligned, and the hardware uses only the implemented bits. On the F4 that is four bits, so priorities 0 to 15 are valid and the rest are ignored. If another library, a vendor BSP or HAL_MspInit changes the grouping later, the same numeric values decode differently. I check SCB->AIRCR PRIGROUP at startup in a debug build and keep all NVIC setup in one function for that reason.

Why grouping matters

With fewer preemption bits, part of the priority becomes subpriority. Subpriority orders pending interrupts of equal preemption priority and affects tail chaining, but it never preempts a running handler. That is the trap in group 0 on the F4: four subpriority bits and zero preemption bits. Safety at priority 0 and telemetry at priority 5 would then sit at the same preemption level, and telemetry would run to completion first if it started first.

PRIGROUPPreemption bitsSubpriority bitsEffect here
440Safety 0 preempts telemetry 5
331Safety 0 preempts telemetry 5
222Safety 0 preempts telemetry 5
113Both decode to preemption 0, no preemption
004No interrupt preempts another

Groups 2 and 3 also work for this pair, because 0 and 5 still differ in the preemption field. Group 4 is the clearest choice when no subpriority ordering is needed, and it removes a class of mistakes where two priorities look different but share a preemption level.

Worked trace

TimeEventCPU
t0Telemetry ISR starts, reads UART FIFOTelemetry handler
t1Safety input asserts, NVIC marks SAFETY pendingTelemetry handler
t2Preemption priority 0 beats 5, context stackedSafety handler
t3Safety clears source, writes safe state, returnsTelemetry resumes

Stacking cost is bounded and small. On Cortex-M4 entry stacks xPSR, PC, LR, R12, R3-R0 plus alignment, roughly 32 bytes, plus the handler frame. That matters for the main stack sizing question, but it does not change the priority decision.

What breaks the guarantee

First, enabling an IRQ before setting its priority. The default priority is 0, so telemetry enabled early can run at the safety level until the later call lands.

Second, FreeRTOS syscall priority. If safety needs xQueueSendFromISR or similar, its priority must be at or below configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY in numeric terms, meaning numerically greater or equal. An ISR above that threshold that calls a FromISR API can corrupt the kernel ready list. If safety must sit above that line, it should do minimal hardware work, set a flag or write a register, and defer the RTOS work to a task.

Third, masking. BASEPRI raised by the kernel, __disable_irq, or a critical section blocks the safety interrupt regardless of NVIC priority. Long critical sections around shared state are therefore a latency bug, not just a style issue. I keep them to a few instructions and never block inside the safety handler on a mutex, a queue with timeout, or a peripheral that telemetry also touches.

Fourth, a shared source. If safety and telemetry share a peripheral interrupt line, priority alone cannot separate them. The handler must demultiplex the source and handle safety first, and the design should split the lines if the safety deadline is tight.

Telemetry ISR running Safety source asserts NVIC compares preemption priorities Safety preempts, telemetry stacked Safety clears source and exits Telemetry resumes

I would verify it on hardware with a scope or logic analyser on two GPIO toggles, one in each handler, and confirm the telemetry pulse is interrupted within the safety deadline rather than merely reordered after it.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-17How would you write a linker script to place a DMA buffer in non-cacheable RAM and define the stack and heap regions on a cache-enabled Cortex-M?

The 90-second answer

I would carve RAM into named MEMORY regions first, then place sections by name instead of letting the linker pack everything into one block. The DMA buffer goes into a region the MPU marks non-cacheable, or into physically separate SRAM with no cache alias. Stack and heap are defined as the two ends of the remaining RAM, with the heap starting after .bss and the stack growing down from the top, so I can check the gap between them in the map file.

Assume a Cortex-M7 with 512 KB cacheable SRAM at 0x20000000, 64 KB SRAM2 at 0x30000000 with no cache alias, a 32-byte cache line, and GNU ld with newlib. Adapt the addresses to the actual part.

LD
MEMORY
{
  FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 1024K
  SRAM  (rwx) : ORIGIN = 0x20000000, LENGTH = 512K
  SRAM2 (rwx) : ORIGIN = 0x30000000, LENGTH = 64K
}

_estack       = ORIGIN(SRAM) + LENGTH(SRAM);  /* 0x20080000, grows down */
_stack_limit  = _estack - 16K;                /* reserve 16 KB for main stack */

SECTIONS
{
  .text :
  {
    *(.text*)
    *(.rodata*)
  } > FLASH

  .data :
  {
    . = ALIGN(8);
    __sdata = .;
    *(.data*)
    __edata = .;
  } > SRAM AT > FLASH

  .bss (NOLOAD) :
  {
    . = ALIGN(8);
    __sbss = .;
    *(.bss*)
    *(COMMON)
    __ebss = .;
  } > SRAM

  .dma_buffer (NOLOAD) :
  {
    . = ALIGN(32);
    __dma_start = .;
    *(.dma_buffer*)
    . = ALIGN(32);
    __dma_end = .;
  } > SRAM2
}

/* Heap is the free gap between __ebss and _stack_limit. */
__heap_start = __ebss;
__heap_end   = _stack_limit;

ASSERT(__ebss < _stack_limit, "no heap left between .bss and stack")
ASSERT(__dma_end <= ORIGIN(SRAM2) + LENGTH(SRAM2), "DMA buffer overflows SRAM2")

The C side declares the buffer into that section and keeps it cache-line aligned:

C
__attribute__((section(".dma_buffer"), aligned(32)))
static uint8_t dma_rx[4096];

Why this layout works

RegionAddress rangeContentsGrowth direction
SRAM20x30000000 to 0x3000FFFF.dma_buffer onlyFixed, sized at link time
SRAM low0x20000000 upward.data, .bssUpward
SRAM middle__ebss to _stack_limitHeap, via _sbrkUpward
SRAM top0x2007C000 to 0x2007FFFFMain stack, 16 KB reservedDownward from _estack

Three details decide whether DMA corrupts memory. First, alignment. The M7 data cache operates on 32-byte lines. If dma_rx starts at offset 16 inside a line, a cache clean or invalidate by the CPU touches neighbouring bytes that belong to another variable. ALIGN(32) on the section and on the symbol keeps the buffer on its own lines. Second, the buffer must not sit in cacheable SRAM unless I add cache maintenance on every transfer. Putting it in SRAM2 removes that requirement, at the cost of using the smaller region and losing cache speed for that buffer. On parts without a second SRAM, the alternative is an MPU region for the buffer with cacheability disabled, plus the same alignment. Third, (NOLOAD) stops the linker emitting initialisation data for it in FLASH. A buffer placed in .data would be copied from FLASH at startup and would land in the cacheable region by default.

Stack and heap need the same explicit treatment. _estack is the initial MSP value loaded by the reset handler from the vector table. If I let the linker place it at the end of .bss instead, the first deep call chain overwrites whatever follows. Reserving the top 16 KB and setting __heap_end to _stack_limit gives a checkable gap.

Newlib does not enforce that gap by default. Its stock _sbrk in libgloss grows a break from the linker symbol end, which GNU ld sets to the end of .bss, and it has no upper bound. Left alone, malloc will grow the heap straight into the stack and the failure appears as a corrupted stack frame. I override it:

C
#include <stddef.h>
#include <stdint.h>

extern char __heap_start;
extern char __heap_end;

void *_sbrk(ptrdiff_t increment)
{
    static char *brk = &__heap_start;
    char *previous = brk;

    if (increment < 0) {
        if (brk + increment < &__heap_start) return (void *)-1;
    } else if (brk + increment > &__heap_end) {
        return (void *)-1;  /* malloc fails instead of hitting the stack */
    }
    brk += increment;
    return previous;
}

Failure modes I check before flashing

The map file tells me most of it. arm-none-eabi-nm on the ELF should show dma_rx inside 0x30000000 to 0x3000FFFF and 32-byte aligned. objdump -h should show .dma_buffer with no LMA in FLASH. If the buffer lands in .bss, the section name in C was misspelled or the linker script lacks the *(.dma_buffer*) input rule, and the linker silently placed it in the default orphan location.

Stack overflow into the heap is harder to see. I fill the reserved stack area with a known pattern at startup, run the worst-case call chain, then scan for the pattern. A watermark that has moved into the heap area means the 16 KB reservation is too small for the nested interrupt depth, which on Cortex-M uses MSP for handlers and PSP for threads under an RTOS. That split is another reason to define the regions in the script: RTOS task stacks are carved from the heap area by the scheduler, while the main and ISR stack stays at _estack.

The last check is the MPU configuration at runtime. A linker script cannot make memory non-cacheable on its own. It only guarantees placement. The MPU setup must mark SRAM2 as non-cacheable, or mark the SRAM region containing the buffer as such, and the cache must be enabled after that setup. If the MPU region is missing, the buffer is still in the right place but the CPU caches it, and DMA writes become invisible until a cache invalidate happens to run. That mismatch is the classic intermittent fault: it works in a debugger session where the cache is off, and fails on the board with the cache on.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-18What does startup code do to .bss before main runs on a microcontroller?

The 90-second answer

Startup code zeroes .bss before main runs. Every object in .bss is uninitialized in C, so the C standard requires it to start as zero. RAM at power-up holds random values, so the reset handler writes zero to the whole section. If that step is skipped, a static buffer keeps whatever was in RAM when power was applied.

Reset ResetHandler Copy .data from flash to RAM Zero .bss in RAM Call main

Where .bss comes from

These declarations land in .bss:

C
static unsigned char rx_buf[256];  /* .bss, must be zero */
static unsigned int tick;          /* .bss, must be zero */
unsigned int retries = 3;          /* .data, must be 3 */
const unsigned int table[4] = {1, 2, 3, 4};  /* .rodata in flash */

.bss occupies RAM but takes no space in the flash image. The linker knows its start and end addresses and emits symbols for them. Startup code uses those symbols to clear the range.

C
/* Simplified startup code, arm-none-eabi-gcc 13 */
extern unsigned int __bss_start__, __bss_end__;

void ResetHandler(void) {
    unsigned int *p = &__bss_start__;
    while (p < &__bss_end__) {
        *p++ = 0;
    }
    main();
}

The loop runs word by word. A 12 KiB .bss needs 3072 iterations. At 168 MHz that takes a few microseconds, before interrupts are enabled.

SectionStored in flashPresent in RAMStartup action
.dataYesYesCopy from flash load address to RAM address
.bssNoYesWrite zero to every word
.textYesExecuted from flashNone

How to spot a missing zeroing step

A bootloader that jumps straight to main without running the application reset handler leaves .bss untouched. The symptom is specific: code runs, initialized globals in .data look correct if the bootloader copied them, and every zero-initialized global holds a stale value. Checking __bss_start__ and __bss_end__ in the map file and confirming the reset handler loops between them catches it. Reading the first word of a static buffer in the debugger at main should show zero. A non-zero value there means the zeroing step never ran or ran over the wrong range.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-19Walk me through how your bootloader verifies a firmware image with CRC and a signature before jumping to the application, and what you do when verification fails or power drops mid-update?

The 90-second answer

I treat CRC and signature as different checks. CRC32 catches a torn write or a bit flip. It does not stop anyone from recomputing the CRC after modifying the image. A signature over the image, checked against a public key fused or stored in immutable bootloader storage, proves the image came from the signing key. The bootloader verifies both, checks the version against an anti-rollback floor, and only then jumps. If either check fails, it never jumps. It boots the other slot if one exists, or stays in recovery.

Assume a Cortex-M33 or similar MCU with an A/B layout, a 512 KB application image, and a bootloader in a separate flash region that the application cannot erase. The header sits at the start of the slot and is not covered by the image CRC in the same way as the payload, so I define the covered range explicitly.

C
/* Checked against C11, Cortex-M33, image in internal flash */
typedef struct {
    uint32_t magic;        /* 0x46574C44 'FWLD' */
    uint32_t header_len;
    uint32_t image_len;    /* payload bytes after header */
    uint32_t version;      /* monotonic, anti-rollback */
    uint32_t crc32;        /* over header fields above + payload */
    uint8_t  sig[64];      /* ECDSA P-256 signature, r||s */
} fw_header_t;

bool verify_slot(uint32_t slot_base) {
    const fw_header_t *h = (const fw_header_t *)slot_base;
    if (h->magic != 0x46574C44u) return false;
    if (h->image_len > SLOT_MAX) return false;
    if (h->version < rollback_floor()) return false;

    uint32_t crc = crc32_update(0xFFFFFFFFu, (const uint8_t *)h,
                                offsetof(fw_header_t, crc32));
    crc = crc32_update(crc, (const uint8_t *)(slot_base + h->header_len),
                       h->image_len);
    if ((crc ^ 0xFFFFFFFFu) != h->crc32) return false;

    /* Verify over the same bytes the signer signed: header fields + payload. */
    return ecdsa_p256_verify(boot_pubkey, slot_base,
                             h->header_len + h->image_len, h->sig);
}

The order matters for cost. CRC32 over 512 KB at roughly 50 MB/s in hardware takes about 10 ms. ECDSA P-256 verification on a Cortex-M33 without a crypto accelerator is typically 80 to 200 ms, and SHA-256 hashing dominates if the accelerator is absent. I run CRC first because it is cheap and catches the common case, a partially written slot after a power cut, before paying for the signature check. On a part with a hardware SHA-256 and ECC block the gap shrinks, but the ordering still holds.

CheckDetectsDoes not detectCost on 512 KB
CRC32Torn write, flash bit error, truncated downloadDeliberate modification with recomputed CRC~10 ms with hardware CRC
ECDSA P-256 signatureAny modification after signing, wrong signing keyReplay of an old signed image, unless version is also checked~80 to 200 ms software, ~20 ms with accelerator
Version vs rollback floorReplay of an older signed imageA new image signed with a stolen keyNegligible

Power loss and the jump

Verification alone does not make an update safe. The update writes the inactive slot, verifies it, and only then flips a slot selector. The selector must survive a power cut halfway through its own write, so I store it as two records with sequence numbers and a CRC, or use a flash word that can only transition in one direction per erase cycle. A torn selector record fails its CRC and the bootloader falls back to the older record. The rollback floor is updated only after the new slot has booted and confirmed itself, otherwise a bad but correctly signed image would permanently block recovery.

No Yes Too old Yes Reset, bootloader runs Read slot metadata CRC and signature pass? Try other slot, else recovery mode Check version vs rollback floor Disable interrupts, stop DMA, clean cache Set VTOR, MSP, jump to reset handler

The jump itself is where I have seen working code fail on the bench. Before jumping I disable interrupts, stop any DMA the bootloader started, clean and invalidate the data cache if the part has one, and set the vector table offset register to the application vector table. I load the application stack pointer from its first vector entry and branch to the reset handler from the second entry, with the link register set to a trap address so a return from reset handler lands somewhere detectable. If the bootloader left the MPU or a clock configuration the application does not expect, the application faults in ways that look like application bugs. I reset the MPU to the state the application expects and document which clocks the bootloader leaves running.

Failure modes I check in review: the signed range and the CRC range disagree, so the header fields an attacker can edit are outside both; the public key is stored in a flash sector the application can erase, which makes the signature check meaningless after the first update; and the bootloader jumps to a slot whose image fits the slot size but whose entry point lies outside the slot. Each of those passes a casual test with a genuine image and fails only under the conditions the check exists for.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-20Walk me through how A/B firmware slots and rollback protect a device if an update fails halfway or boots badly?

The 90-second answer

Keep two copies of the application in flash, A and B, and never overwrite the copy you are running from. The bootloader boots one slot, the updater writes the new image into the other slot, verifies it, and only then flips a boot flag. If the new image crashes, times out, or never confirms itself, the bootloader falls back to the old slot on the next reset.

Assume a 512 KB internal flash part split as 256 KB per slot, with a separate metadata sector the application never writes directly. The running slot stays bootable for the entire download and write. That is the whole protection: a failed update damages only the inactive slot.

no yes yes no yes no Bootloader reads metadata Selected slot CRC and signature OK? Boot other slot Boot selected slot in trial mode App confirms within N boots? Mark slot confirmed, clear trial Bootloader increments fail count Fail count exceeded?

Metadata and the atomic flip

The bootloader trusts metadata, not the application, so metadata needs its own integrity check and a way to survive a torn write. A common layout is two metadata copies in separate flash sectors, each with a sequence number and CRC32. The bootloader picks the valid copy with the higher sequence.

C
// Checked against a bootloader written in C for a Cortex-M4, 256 KB slot
typedef struct {
    uint32_t seq;            // increments on every flip
    uint32_t active_slot;    // 0 = A, 1 = B
    uint32_t trial_slot;     // slot pending confirmation, 0xFFFFFFFF = none
    uint32_t boot_attempts;  // attempts for trial_slot
    uint32_t min_version;    // anti-rollback floor
    uint32_t crc32;          // over all fields above
} boot_meta_t;

Update sequence, with a worked trace for a power cut:

StepActionState if power cuts here
1Updater erases inactive slot B, streams image, writes in 4 KB pagesA still active, B partial and ignored
2Updater computes SHA-256 over B, checks signature with vendor public keyB not yet marked bootable
3Updater writes new metadata copy: trial_slot=B, boot_attempts=0, seq+1Bootloader sees valid trial request
4Reset. Bootloader verifies B hash, boots B, sets boot_attempts=1 in RAM or metadataIf B crashes before confirm, next reset increments again
5B runs self-tests (sensors, comms, watchdog kick) and writes confirmed metadataA remains fallback until this write lands

Step 3 is the only point where the device changes its mind, and it happens after verification. Writing metadata before step 2 would let a truncated image become the boot target.

Confirmation and rollback

A new image that passes CRC can still be wrong for the hardware. It might initialise the wrong clock tree, hang in a driver probe, or pass its own tests while breaking a field function. Trial mode handles that. The bootloader allows, say, 3 attempts. The application must explicitly confirm after its checks pass. A hardware watchdog, typically 2 to 5 seconds on these parts, covers the case where B hangs before it can confirm or crash.

On the third failed attempt the bootloader clears the trial flag, marks B invalid, and boots A. It should also report the failure on next successful boot, through a status flag or a log entry in a wear-levelled sector, so the device can retry the download later instead of silently staying on an old version forever.

Trade-offs and failure modes

Design choiceCostWhen it bites
A/B with 256 KB slots on 512 KB flashNo room for a large application plus a recovery imageA 300 KB application forces external flash or a compressed delta update
CRC32 onlyCheap, catches torn writesDoes not stop a crafted image, so add signature check for field devices
Confirm after 1 bootFast rolloutA fault that appears only under load or after 10 minutes never triggers rollback
Confirm after self-tests plus a soak timerCatches more bad imagesDelays fleet rollout and needs a timer that survives reset

Three failure modes I would name in an interview:

  1. Metadata sector corruption. If both metadata copies sit in one sector, a single bad erase can brick the device. Keep copies in separate sectors, never erase both in one operation, and keep the bootloader itself in a protected region that the updater cannot erase.
  2. Rollback to a vulnerable version. An attacker who can trigger a crash can force the device back to an old slot with a known bug. The min_version field above, stored in one-time-programmable fuses or a monotonic counter, blocks downgrades below a floor once a security fix has been confirmed.
  3. Slot B boots but never confirms because confirmation depends on the network. If confirmation requires a server round trip, a device in a tunnel will roll back a good update. Confirmation should depend on local self-tests, with server reporting as a separate, non-blocking step.

External SPI flash changes the arithmetic but not the mechanism. With 8 MB of external flash you can keep A and B internally and stage the download externally, then copy and verify before flipping. The bootloader still needs a small internal recovery path if the internal copy is corrupt, which is why many designs keep a minimal recovery bootloader that can re-copy from external flash without a full application running.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-21A pointer in RAM keeps changing to a bad value during a run. How would you use a hardware watchpoint over SWD to catch the exact write, and what would you inspect when the core halts?

The 90-second answer

I would put a hardware watchpoint on the pointer itself and let the core run until something writes it. A breakpoint stops at a chosen instruction. A watchpoint stops at a chosen address, which is what I need when I know the victim but not the culprit. On a Cortex-M4 over SWD, that watchpoint is a DWT comparator. It watches the address on every core load and store and halts the core when the access matches.

I would get the address from the ELF file for the build on the board, set a write watchpoint for the exact size of the pointer, continue, and then read the PC, registers and memory around the pointer at the halt. The PC names the store. The registers show whether the pointer value or the address calculation went wrong.

Setting it up

First, confirm the address. If the pointer is a global, nm firmware.elf gives it. If it is a struct field, add the field offset to the struct address. A 32-bit pointer at 0x20001A4C needs a 4 byte watchpoint at that address, not at the start of the struct.

In GDB with OpenOCD or a vendor probe:

GDB
target extended-remote :3333
file firmware.elf
break main
continue
watch *(volatile uint32_t *)0x20001A4C
continue
info registers
x/8xw 0x20001A40
bt

watch on a Cortex-M target programs a DWT comparator. Most M4 parts have 4 comparators, so I can watch up to 4 addresses at once. The comparator holds the address, the size mask and the access type. I set write only, because a read watchpoint would halt on every legitimate use of the pointer and bury the write I care about.

SWD and JTAG both reach the same DWT registers through the debug port. SWD needs SWCLK, SWDIO, ground and reset. JTAG needs more pins. On a board wired for SWD, I use SWD and the watchpoint behaviour is identical.

Reading the halt

When the write happens, the core halts and the debugger reports the PC of the store instruction. I check three things in order.

  1. The PC and backtrace. This tells me which function performed the store and who called it.
  2. The registers. The register holding the value being stored shows the new pointer value. The register holding the destination address shows whether the store went to the right place.
  3. Memory around the victim. x/8xw above dumps the pointer and its neighbours. One changed word with intact neighbours points to a single bad store. A run of changed words points to an overrun or a copy with a wrong length.

A typical trace looks like this:

HaltPCPointer after writeWhat the registers show
10x080012340x20003B00r0 holds a valid heap address, intended write
20x08001B7C0x2000F3A8r1 holds a stack address, wrong source

Halt 2 is the bug. The store at 0x08001B7C wrote a stack address into a pointer that should hold a heap address. I would set a breakpoint at that PC, rerun, and inspect the pointer variable before the store to see where the stack address came from. A common cause is returning the address of a local variable or copying an uninitialised struct.

Limits to keep in mind

The DWT only sees core accesses. A DMA engine writing to RAM does not pass through the core, so a DMA overrun can change the pointer without tripping the watchpoint. If the memory changes but the watchpoint never fires, I stop DMA and rerun. If the corruption stops, I check DMA transfer counts and buffer limits.

Optimised code can also move the store or keep the pointer in a register, which makes the PC harder to read. If the trace looks odd, I rebuild the suspect file at -O0 -g, confirm the bug still reproduces, and repeat the watchpoint. The watchpoint itself still works, but the register evidence is easier to trust at low optimisation.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-22How do ITM/SWO trace and a GPIO toggle let you measure jitter in a control loop without halting the CPU?

The 90-second answer

Toggle a GPIO at the top of the control loop and measure that pin with a scope or logic analyser. That gives you period, pulse width and jitter directly, with no debugger attached and no halt. Add ITM over SWO when you also need the numbers behind the waveform, such as cycle counts per iteration, because a scope shows when jitter happens but not why.

On Cortex-M, the DWT cycle counter (CYCCNT) timestamps the loop, and ITM stimulus ports send those timestamps out the single SWO pin while the core keeps running. A breakpoint or a halted printf over a serial console would stop or delay the loop and destroy the timing you are trying to measure. SWO does not halt the core, so the loop under test stays live.

GPIO toggle: the first probe

C
/* Cortex-M4 at 168 MHz, GPIO pin already configured as push-pull output */
static inline void loop_mark(void) { GPIOA->ODR ^= GPIO_PIN_8; }

static inline void trace_u32(uint32_t v)
{
    for (int i = 0; i < 4; i++) {
        ITM_SendChar(0, (char)((v >> (8 * i)) & 0xFFu));
    }
}

void dwt_init(void)
{
    CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
    DWT->CYCCNT = 0;
    DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}

void control_loop(void)
{
    dwt_init();
    for (;;) {
        loop_mark();              /* rising edge: start of iteration */
        uint32_t t0 = DWT->CYCCNT;
        run_pid_and_outputs();
        uint32_t cycles = DWT->CYCCNT - t0;  /* unsigned, wrap-safe */
        trace_u32(cycles);
    }
}

Wire PA8 to a scope probe with a short ground spring. A 1 kHz loop should show a 1.000 ms period. If the period wanders between 998 us and 1,014 us, jitter is 16 us peak to peak, about 1.6% of the period. At 168 MHz one cycle is 5.95 ns, so 16 us is roughly 2,688 cycles. That scale tells you whether to chase an ISR, a bus stall, or a clock problem.

MethodWhat you getCost to the loopLimit
GPIO toggle + scopePeriod, pulse width, jitter, missed deadlines2 to 3 cycles per toggleNo cause, no per-iteration values
DWT CYCCNT + ITM/SWOCycle count per iteration, min/max, occasional samplesTens of cycles if you send rarelySWO bandwidth, trace buffer overflow
Breakpoint / halted printfFull register and stack stateHalts the core, timing invalidUseless for jitter under load

ITM/SWO: numbers without a halt

Enable ITM and the SWO pin in the debugger or in code, route a stimulus port to SWO, and decode it in the IDE (OpenOCD, Segger Ozone, Keil, or STM32CubeIDE all support SWO trace). Send compact binary data, not formatted text, from inside the loop. A 4-byte cycle count at 1 kHz is 4 kB/s, trivial for a 2 Mbaud SWO clock. A printf per iteration is not: at 115200 baud a 20-byte line costs about 1.7 ms of wire time and will either block or overflow the ITM FIFO.

Control loop iteration GPIO toggle Scope measures period and jitter DWT CYCCNT timestamp ITM stimulus port SWO pin Host decoder logs cycles Correlate jitter spikes with cycle counts

Worked trace

At 168 MHz, a 1.000 ms iteration is 168,000 cycles. Suppose the scope shows a clean 1.000 ms period for 900 iterations, then one 1.012 ms period. The SWO log for that iteration shows 170,016 cycles instead of the usual 168,000. The difference is 2,016 cycles, which is 12 us at 168 MHz, and it matches the 12 us scope deviation exactly. You have bounded the fault to a 12 us disturbance, consistent with a short ISR or a DMA burst, rather than a missed tick or a blocking call.

You can then add a second GPIO toggle around the suspected block, such as the sensor read or the output update, to split the loop into sections and see which section absorbs the extra 2,016 cycles.

Failure modes to watch

SWO overflow silently drops trace packets when the host cannot keep up, so a gap in the log does not mean the loop stopped. Keep the SWO clock at 2 MHz or higher, send binary, and sample every Nth iteration if bandwidth runs out. GPIO toggles also load the pin: a long scope lead adds ringing that looks like jitter, so use a short ground and confirm the edge rate on the scope before blaming firmware. Finally, CYCCNT wraps every 25.5 seconds at 168 MHz (2^32 / 168e6), so compute differences with unsigned subtraction, as in the snippet, and the wrap cancels out.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-23A peripheral streams 200 bytes every 10 ms while another raises one interrupt per byte at 200 Hz. How do you choose polling, interrupts or DMA for each, and what CPU cost calculation justifies it?

The 90-second answer

Assume a Cortex-M4 at 168 MHz, a peripheral that can signal readiness, and a latency deadline stated in microseconds rather than milliseconds. I choose by events per second multiplied by cost per event, not by habit. Polling wins when the CPU has nothing else to do and the deadline is tighter than interrupt latency. Interrupts win for sparse, latency sensitive events. DMA wins when data arrives in blocks and per byte handling would consume the CPU or jitter the deadline.

For your two cases: the 200 byte block every 10 ms is 20,000 bytes per second and 100 blocks per second. DMA with one interrupt per block is the right default. The single byte at 200 Hz is 200 interrupts per second. An interrupt per byte is cheap there, and DMA setup plus waiting to fill a block would add latency for no gain.

The arithmetic that decides it

Hypothetical but realistic figures for a Cortex-M4, checked against the core entry sequence: interrupt entry stacks 8 registers in about 12 cycles, a small handler that reads one byte and writes a ring buffer takes about 40 cycles, exit takes about 10 cycles. Call it 62 cycles per byte interrupt. A tight polling loop that loads the status register, tests a flag, loads data and loops takes about 10 cycles per iteration, so it can spin at roughly 16.8 million iterations per second and burn the whole core while doing it.

| Scheme | Cost per event | At 20,000 bytes/s | At 200 events/s | Latency behaviour | | --- | --- | --- | --- | | Polling, spinning | 10 cycles per iteration, continuous | 100% CPU if spinning | 100% CPU if spinning | Lowest, limited by loop time | | Polling, periodic wake every 100 us | 10 cycles per poll, 10,000 polls/s | 100,000 cycles/s, 0.06% | 100,000 cycles/s, 0.06% | Up to 100 us late | | Interrupt per byte | 62 cycles per byte | 1.24M cycles/s, 0.74% | 12,400 cycles/s, 0.007% | About 0.4 us plus priority delay | | DMA, interrupt per 200 byte block | About 150 cycles setup plus 62 cycles completion interrupt per block | 21,200 cycles/s, 0.013% | Not applicable, block never fills | One block delay unless using half transfer |

The crossover is not at 20,000 bytes per second. Per byte interrupts still look cheap there. It moves when the rate reaches hundreds of thousands per second, when the handler grows, or when jitter matters. At 500,000 bytes per second, per byte interrupts cost 31M cycles per second, about 18% of the core, before the task that consumes the data runs at all. At 2 MHz they saturate it. DMA cost stays flat per block, so block size is the lever. A 16 byte block at the same byte rate costs twelve times more DMA interrupts than a 200 byte block.

Polling has a different failure mode. Spinning looks free in a table until it starves a lower priority task, blocks sleep, or keeps the bus clocked and drains the battery. Periodic polling fixes the power problem and creates a latency floor equal to the poll period. If the deadline is 20 us and you poll every 100 us, you will miss it even though average CPU looks fine.

Single, sparse Yes No Block Yes No Yes No Data arrives Block or single event? Deadline under 2 us? Poll or DMA with fast wake Interrupt per event Bytes per second over 100k or handler heavy? DMA, interrupt per block or half block CPU idle most of the time? Polling with sleep between polls

How I would implement the block case

DMA in circular mode into a buffer twice the block size, with a half transfer interrupt so the task can process the first 200 bytes while the second half fills. That halves the worst case latency compared with waiting for the full buffer, at the cost of twice as many interrupts, still only 200 per second here.

C
/* Cortex-M4, DMA1 Stream for UART RX, circular, half transfer IRQ */
#define RX_BUF_SIZE 400
static uint8_t rx_buf[RX_BUF_SIZE];

void dma_init(void) {
    DMA1->S0CR = DMA_SxCR_CIRC | DMA_SxCR_MINC | DMA_SxCR_TCIE
              | DMA_SxCR_HTIE | DMA_SxCR_CHSEL_2; /* channel 4 on many STM32F4 */
    DMA1->S0PAR = (uint32_t)&USART1->DR;
    DMA1->S0M0AR = (uint32_t)rx_buf;
    DMA1->S0NDTR = RX_BUF_SIZE;
    DMA1->S0CR |= DMA_SxCR_EN;
}

void DMA1_Stream0_IRQHandler(void) {
    if (DMA1->HIFCR & DMA_HIFCR_HTIF0) {
        DMA1->HIFCR = DMA_HIFCR_HTIF0;
        queue_push_block(rx_buf, RX_BUF_SIZE / 2); /* first half ready */
    }
    if (DMA1->HIFCR & DMA_HIFCR_TCIF0) {
        DMA1->HIFCR = DMA_HIFCR_TCIF0;
        queue_push_block(rx_buf + RX_BUF_SIZE / 2, RX_BUF_SIZE / 2);
    }
}

Two checks before I trust this. First, cache. On a cache enabled part the DMA writes bypass the cache, so the CPU must invalidate the cache lines covering rx_buf before reading, or place the buffer in a non cacheable region. Second, overrun. DMA removes the per byte CPU cost but it does not remove the consumer. If the task stalls for 30 ms, the circular buffer wraps and the oldest bytes are overwritten silently. I would count wraps in the half transfer handler and expose that counter, because a wrap counter that stays at zero in testing and jumps in the field tells you the consumer, not the transfer, is the bottleneck.

For the 200 Hz single byte peripheral I would keep the interrupt, set its priority above telemetry and below any safety source, and keep the handler to reading the register and advancing a single producer ring index. No DMA channel tied up, no block latency, and the measured cost is negligible. If that rate later rose to 50,000 Hz, I would remeasure the handler with a GPIO toggle and a scope, and move to DMA only when the interrupt load or the jitter on a higher priority task showed up in the trace.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-24A UART interrupt can fire before uart_init() has finished. How do you stop the ISR corrupting the receive buffer, and what do you lose by masking it until init is done?

The 90-second answer

Mask the interrupt until the driver is ready, and enable it last. On Cortex-M that means the peripheral interrupt enable bit and the NVIC enable bit both stay clear from reset. Clear any pending bit, initialize the ring buffer and its indices, then set a ready flag, then enable the peripheral, then enable the NVIC. The ISR also checks the ready flag and clears the hardware source before returning, in case the line was already asserted by a bootloader or by hardware before your code ran.

Without that guard, an early entry runs against zeroed .bss. It can write a received byte into a buffer that is not valid yet, advance a head index past the tail, or call a callback pointer that is still NULL. The ISR returns cleanly, so the corruption shows up later as a driver bug that is hard to trace back to boot.

C
/* Cortex-M4, STM32-style USART and NVIC */
static volatile bool uart_ready;
static uint8_t rx_buf[256];
static volatile uint16_t rx_head, rx_tail;

void USART2_IRQHandler(void)
{
    uint32_t sr = USART2->SR;
    USART2->SR = 0; /* clear the source before any early return */
    if (!uart_ready) {
        return;
    }
    if (sr & USART_SR_RXNE) {
        uint16_t next = (rx_head + 1) & 0xFF;
        if (next != rx_tail) {
            rx_buf[rx_head] = (uint8_t)USART2->DR;
            rx_head = next;
        }
    }
}

void uart_init(void)
{
    USART2->CR1 &= ~USART_CR1_RXNEIE;
    NVIC_DisableIRQ(USART2_IRQn);
    NVIC_ClearPendingIRQ(USART2_IRQn);

    rx_head = rx_tail = 0;
    memset(rx_buf, 0, sizeof(rx_buf));
    USART2->BRR = 0x8B; /* 115200 baud example */
    USART2->CR1 |= USART_CR1_UE | USART_CR1_RE | USART_CR1_TE;

    uart_ready = true;
    __DMB();
    USART2->CR1 |= USART_CR1_RXNEIE; /* peripheral first */
    NVIC_EnableIRQ(USART2_IRQn);     /* NVIC last */
}

The order matters because of the pending bit. Enable the NVIC before clearing pending and a byte that arrived during clock setup enters the ISR before the buffer is valid. Clear pending after enabling and the same window opens. Clearing while disabled, then enabling the peripheral, then the NVIC, closes both windows. The ready check covers the case where the peripheral was left enabled by a bootloader and its line is already active.

Masking has a cost. Events that arrive during init are lost or delayed, so the right choice depends on whether they can be recovered.

ApproachWhen it fitsWhat you lose
Mask until ready, discard early eventsTelemetry or logging where the sender resendsBytes received during init
Mask, then poll and drain the FIFO before enablingUART or SPI with a hardware FIFONothing, if you drain before the FIFO overruns

For the drain option, poll RXNE in a bounded loop after configuring the peripheral but before setting uart_ready, store those bytes through the same ring buffer path, then enable the interrupt. For a peripheral with no FIFO, such as a timer compare, there is nothing to drain. The event is gone, so you either accept the loss or hold the source in reset until init finishes.

A simple check catches the bootloader case. Count entries taken while uart_ready is false and expose that counter in a fault dump. A nonzero count means hardware is asserting the line earlier than your init sequence assumes, which points to reset state or a floating pin rather than a bug in the ISR itself.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-25Your UART ISR clears the NVIC pending bit before the peripheral flag, and you see a spurious second entry with no new byte. What order do you clear things in, and why does the reverse order re-enter?

The 90-second answer

Clear the source first, then the NVIC pending bit, then re-enable. On most STM32 peripherals that means: mask the interrupt at the peripheral or in the NVIC, clear the peripheral flag (write 1 to the clear bit, or read the status/data register that clears it), clear the NVIC pending bit with NVIC_ClearPendingIRQ(), drain any FIFO or data register, and only then unmask. Reversing the first two steps leaves the hardware source still asserting while the CPU thinks the interrupt is done, so the NVIC re-pends it immediately and you get a spurious entry with no new event.

The reason is that there are two latches in series. The peripheral sets its own flag, for example USART_SR.RXNE or EXTI_PR, and that flag requests the NVIC. The NVIC then sets its pending bit and, if enabled, vectors to the handler. Clearing only the NVIC bit removes the second latch. The peripheral flag is still set, so the NVIC sets pending again as soon as the handler returns, or even before it returns if the interrupt is re-enabled. Clearing only the peripheral flag leaves a stale NVIC pending bit, which fires once on return even though the source is quiet. Both latches must be cleared, source first.

C
// STM32F4-style USART1 receive ISR, checked against CMSIS and RM0368
void USART1_IRQHandler(void)
{
    uint32_t sr = USART1->SR;          // snapshot before any clear
    if (sr & USART_SR_RXNE) {
        uint8_t byte = (uint8_t)USART1->DR;  // reading DR clears RXNE
        ring_push_isr(byte);
    }
    if (sr & USART_SR_ORE) {
        USART1->SR;                    // read SR, then read DR: clears ORE
        (void)USART1->DR;
    }
    NVIC_ClearPendingIRQ(USART1_IRQn); // second latch, cleared last
}

Two details in that snippet matter. First, the snapshot sr is taken before clearing, because reading DR changes SR. Second, some flags do not clear on read. On STM32, EXTI_PR clears by writing 1 to the bit, and writing 0 has no effect. USART_SR.ORE clears only with the read-SR-then-read-DR sequence. Writing a generic clear mask to the wrong register does nothing, and the interrupt re-enters forever.

OrderPeripheral flagNVIC pendingResult
------------
------------
------------
Source, then NVICclearedclearedhandler runs once per event
NVIC, then sourcecleared latecleared earlysource re-pends NVIC, spurious second entry
Source onlyclearedleft setone stale entry on return
NVIC onlyleft setclearedimmediate re-entry loop

Where the order gets subtle

Clearing at the start of the ISR versus the end is a real trade-off. Clear early and a new event that arrives during a long handler can set the flag again and be handled promptly, but if you clear after reading the data register you can erase that new event. Clear late and you risk the re-entry described above if the interrupt is unmasked during the handler. The safe pattern for a level-sensitive source is to mask it on entry, clear the source, do the work, clear the NVIC pending bit, then unmask. For an edge-triggered source such as a GPIO EXTI line, clear the EXTI_PR bit for the lines you handled, and check the snapshot, because several lines can share one vector.

Vector taken Mask source in NVIC Snapshot peripheral status Clear peripheral flag or read DR Do work from snapshot Clear NVIC pending bit Unmask source

A new byte arriving between steps D and F sets the peripheral flag again. Because the source is masked, it does not preempt, but the flag survives step F, so after step G the NVIC pends and the handler runs again with real data. That is the behaviour you want. If you unmask before step D, that same byte can re-enter mid-handler and corrupt a non-reentrant buffer.

Failure modes to name in the interview

A handler that clears the NVIC bit in main or in a deferred task, long after the ISR returned, leaves a window where the peripheral flag re-pends the NVIC and the CPU vectors into an ISR whose data register is already empty. Reading an empty DR returns the last byte again, which looks like a duplicated frame on the wire. A shared vector cleared with a blanket write, such as writing all ones to EXTI_PR, also clears lines you never serviced, so their events are lost silently. The fix is to clear only the bits present in the snapshot.

On Cortex-M, NVIC_ClearPendingIRQ() writes to NVIC_ICPR. That register is write-only for clearing, and it does not touch the peripheral. On some older or vendor-specific peripherals the order is documented differently, for example a timer capture flag that clears on reading CCRx. The rule that survives those exceptions is to follow the reference manual sequence for that flag, and to treat the NVIC bit as the last thing cleared before re-enabling.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-26On STM32, how do you set and clear a GPIO pin with BSRR so the write does not need a read-modify-write on ODR?

The 90-second answer

Use the port's bit set/reset register instead of the output data register. On STM32F4 parts that register is BSRR at offset 0x18. Writing a 1 in bits 15:0 sets the matching pins, writing a 1 in bits 31:16 clears them, and writing 0 leaves a pin unchanged. That makes a single store change one pin, with no read of the current value.

Assume GPIOA, pins 0 to 15, and the RCC clock for the port is already enabled. The register block is memory mapped, so the driver describes it as a struct of volatile 32-bit words at the base address.

C
/* STM32F4, GPIOA base 0x40020000, RM0368 */
#include <stdint.h>

typedef struct {
    volatile uint32_t MODER;   /* 0x00 */
    volatile uint32_t OTYPER;  /* 0x04 */
    volatile uint32_t OSPEEDR; /* 0x08 */
    volatile uint32_t PUPDR;   /* 0x0C */
    volatile uint32_t IDR;     /* 0x10 */
    volatile uint32_t ODR;     /* 0x14 */
    volatile uint32_t BSRR;    /* 0x18 */
    volatile uint32_t LCKR;    /* 0x1C */
    volatile uint32_t AFR[2];  /* 0x20 */
} GPIO_TypeDef;

#define GPIOA ((GPIO_TypeDef *)0x40020000UL)

static inline void gpio_set(uint8_t pin)
{
    GPIOA->BSRR = (1UL << pin);
}

static inline void gpio_clear(uint8_t pin)
{
    GPIOA->BSRR = (1UL << (pin + 16));
}

Configuration uses masking because several pins share one register. MODER holds a 2-bit field per pin, so pin 5 occupies bits 11:10. Clearing that field with MODER &= ~(3UL << 10) and then setting it to output with MODER |= (1UL << 10) changes pin 5 and leaves the other fifteen fields alone. The same mask pattern applies to OSPEEDR and PUPDR, with the shift equal to pin * 2.

Why ODR needs a different approach

ODR has no set or clear bits. Changing one pin through ODR means reading the register, modifying the bit in a CPU register, and writing the whole word back. An interrupt that changes another pin between the read and the write gets overwritten by the stale value.

StepContextActionODR
1TaskReads ODR0b00000000
2ISRSets pin 70b10000000
3TaskWrites back its copy with pin 3 set0b00001000

Pin 7 is lost at step 3. With BSRR, the task writes only the bit for pin 3. The hardware ignores the other bits, so the ISR's change to pin 7 survives. That is the atomicity the set/reset register provides: one store, one pin affected.

Two checks catch most mistakes. First, confirm the port clock is enabled in RCC_AHB1ENR, since writes to a clock-gated port have no effect on the pin. Second, keep the pin number within 0 to 15 for this register, since a larger value shifts into the opposite half of BSRR and clears a different pin. For reading the actual pin state, use IDR rather than ODR, because ODR only shows the value the core requested.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-27How would you decode a 32-bit hardware status register portably in C using unions, masks and bitfields, and what breaks if you rely on bitfield layout alone?

The 90-second answer

I would decode with explicit masks and shifts as the source of truth, and use a union with a bitfield view only as a checked convenience layer. A bitfield layout is implementation-defined in C: allocation order, whether a field crosses a storage unit, padding, and the effect of endianness are not portable. Masks are portable because shift and mask semantics on an unsigned integer are defined. If I ship bitfields, I guard them with static_assert on size and on the offset of a known field, and I never use them for a register where a read-modify-write would clear write-1-to-clear flags.

Take a 32-bit status register, little-endian peripheral, checked against C11 and GCC/Clang for ARM:

BitsFieldMeaning
0READY1 = data available
1BUSY1 = conversion running
2ERR1 = fault, write 1 to clear
3OVERRUN1 = overrun, write 1 to clear
7:4FIFO_LEVEL0 to 15 entries
15:8IRQ_ENinterrupt enables, mirrored in status
31:16RESERVEDmust be ignored on read, written as 0

Portable decode, no layout assumption:

C
#include <stdint.h>
#include <stdbool.h>

#define REG_READY      (1u << 0)
#define REG_BUSY       (1u << 1)
#define REG_ERR        (1u << 2)
#define REG_OVERRUN    (1u << 3)
#define REG_FIFO_MASK  (0xFu << 4)
#define REG_IRQEN_MASK (0xFFu << 8)

typedef struct {
    bool ready;
    bool busy;
    bool err;
    bool overrun;
    uint8_t fifo_level;
    uint8_t irq_en;
} status_t;

static inline status_t decode_status(uint32_t raw)
{
    status_t s;
    s.ready       = (raw & REG_READY) != 0;
    s.busy        = (raw & REG_BUSY) != 0;
    s.err         = (raw & REG_ERR) != 0;
    s.overrun     = (raw & REG_OVERRUN) != 0;
    s.fifo_level  = (uint8_t)((raw & REG_FIFO_MASK) >> 4);
    s.irq_en      = (uint8_t)((raw & REG_IRQEN_MASK) >> 8);
    return s;
}

Worked trace for raw = 0x0000123Du:

StepOperationResult
READY0x123D & 0x11, ready
BUSY0x123D & 0x20, not busy
ERR0x123D & 0x41, fault set
OVERRUN0x123D & 0x81, overrun set
FIFO_LEVEL(0x123D >> 4) & 0xF0x3, 3 entries
IRQ_EN(0x123D >> 8) & 0xFF0x12

The bitfield view, used only after the mask decode is proven:

C
typedef union {
    uint32_t raw;
    struct {
        uint32_t ready      : 1;
        uint32_t busy       : 1;
        uint32_t err        : 1;
        uint32_t overrun    : 1;
        uint32_t fifo_level : 4;
        uint32_t irq_en     : 8;
        uint32_t reserved   : 16;
    } bits;
} status_reg_t;

_Static_assert(sizeof(status_reg_t) == 4, "status register must be 32-bit");

That union is safe for reading on the target compiler because the union type-punning is defined in C11, and the static_assert catches a compiler that pads the struct. It is not portable across endianness. On a big-endian target the first declared bitfield occupies the most significant bits of the storage unit in most implementations, so ready would land at bit 31, not bit 0. The mask version above is unchanged. I would also refuse to write through the bitfield view to a write-1-to-clear register. A bitfield store is a read-modify-write of the whole storage unit, so clearing ERR by writing 0 to that field can write back a 1 to OVERRUN if it was set between the read and the write, and clear it unintentionally. For writes I build the value with masks and write the full uint32_t once, or write only the clear bits.

Two failure modes I check in review. First, reserved bits: if a future silicon revision adds a field at bit 16, code that masks with 0xFFFF ignores it, code that compares the whole register to a known value breaks. Second, signed shifts: I keep the register uint32_t and cast before shifting, because right-shifting a negative signed value is implementation-defined and left-shifting into the sign bit is undefined. If the register is volatile memory-mapped, I read it once into a local uint32_t and decode the local, so a status that changes mid-decode cannot give me READY from one sample and FIFO_LEVEL from the next.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-28How would you configure an STM32 timer for 1 kHz PWM output and measure a pulse width with input capture on the same timer?

The 90-second answer

I would use one timer for PWM output and a second timer, or a second channel group, for input capture. I would not try to run PWM output and PWM input mode on the same timer at the same time, because PWM input mode resets the counter on the input edge and remaps the capture channels. For PWM I set prescaler and auto-reload from the timer clock, use PWM mode 1 with preload, and write the compare value for duty. For pulse measurement I use PWM input mode, where channel 1 captures the rising edge and channel 2 captures the falling edge, and I read both capture registers in the falling-edge callback.

Assume TIM2 on an STM32G4 with PCLK1 at 170 MHz and the APB prescaler at 1, so the timer clock is 170 MHz. I check that assumption first. On many STM32 parts the timer clock doubles when the APB prescaler is not 1, so a frequency worked out from the CPU clock alone can be wrong by a factor of two.

PWM output

Counter frequency is f_cnt = f_tim / (PSC + 1). PWM frequency is f_pwm = f_cnt / (ARR + 1). In PWM mode 1 the output is active while CNT < CCR, so duty is CCR / (ARR + 1).

For 1 kHz with 0.1 percent duty steps I want a 1 MHz counter and a 1000 tick period. That gives PSC = 169 and ARR = 999. A compare value of 250 gives 25 percent duty, and changing CCR by 1 changes duty by 0.1 percent. The trade-off is direct. A larger ARR gives finer duty resolution but a lower PWM frequency for the same counter clock, and a larger PSC lowers the counter clock and coarsens both.

C
TIM_HandleTypeDef htim2;
TIM_OC_InitTypeDef oc = {0};

htim2.Instance = TIM2;
htim2.Init.Prescaler = 169;      /* 170 MHz / 170 = 1 MHz */
htim2.Init.Period = 999;         /* 1 MHz / 1000 = 1 kHz */
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
HAL_TIM_PWM_Init(&htim2);

oc.OCMode = TIM_OCMODE_PWM1;
oc.Pulse = 250;                  /* 25 percent */
oc.OCPolarity = TIM_OCPOLARITY_HIGH;
oc.OCFastMode = TIM_OCFAST_DISABLE;
HAL_TIM_PWM_ConfigChannel(&htim2, &oc, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);

Auto-reload preload and compare preload keep a duty change made mid-cycle from producing a runt pulse. Without preload, writing CCR just before the counter reaches it can shorten or lengthen one cycle. I also set the GPIO alternate function for PA0/TIM2_CH1 and confirm the pin is not still assigned to a previous timer mapping.

Input capture for pulse width

For a pulse on PA0 I use PWM input mode. Channel 1 is mapped to TI1 and captures rising edges. Channel 2 is also mapped to TI1 but captures falling edges. The slave controller resets the counter on the TI1 rising edge, so CCR1 holds the period in counter ticks and CCR2 holds the high time in counter ticks. With the same 1 MHz counter, one tick is 1 us.

C
TIM_IC_InitTypeDef ic = {0};

htim2.Init.Prescaler = 169;
htim2.Init.Period = 0xFFFFFFFF;  /* free-running 32-bit counter */
HAL_TIM_IC_Init(&htim2);

ic.ICPolarity = TIM_ICPOLARITY_RISING;
ic.ICSelection = TIM_ICSELECTION_TI1;
ic.ICPrescaler = TIM_ICPSC_DIV1;
ic.ICFilter = 4;
HAL_TIM_IC_ConfigChannel(&htim2, &ic, TIM_CHANNEL_1);

ic.ICPolarity = TIM_ICPOLARITY_FALLING;
HAL_TIM_IC_ConfigChannel(&htim2, &ic, TIM_CHANNEL_2);

TIM_SlaveConfigTypeDef slave = {0};
slave.SlaveMode = TIM_SLAVEMODE_RESET;
slave.InputTrigger = TIM_TS_TI1FP1;
slave.TriggerPolarity = TIM_TRIGGERPOLARITY_RISING;
slave.TriggerPrescaler = TIM_TRIGGERPRESCALER_DIV1;
slave.TriggerFilter = 4;
HAL_TIM_SlaveConfigSynchro(&htim2, &slave);

HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_1);
HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_2);

The pairing matters. CCR1 is captured at the rising edge, and CCR2 is captured only at the later falling edge. Reading both registers in the channel 1 callback would pair the new period with the previous cycle's high time. I therefore read both in the channel 2 callback, where the falling edge has just been captured and both values belong to the same cycle.

C
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
    if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2) {
        uint32_t period = __HAL_TIM_GET_CAPTURECOMPARE(htim, TIM_CHANNEL_1);
        uint32_t high   = __HAL_TIM_GET_CAPTURECOMPARE(htim, TIM_CHANNEL_2);
        if (high <= period) {
            pulse_period_us = period;  /* 1 tick = 1 us at 1 MHz */
            pulse_high_us   = high;
        } else {
            glitch_count++;            /* missed or noisy edge */
        }
    }
}

A worked trace with a 1 MHz counter looks like this:

EventCCR1 period (ticks)CCR2 high time (ticks)Result
Pulse A10000250010 ms period, 2.5 ms high, 25 percent
Pulse B50005005 ms period, 0.5 ms high, 10 percent
Pulse C100002500same as A, counter reset each rising edge

Conversion is time_us = ticks * (PSC + 1) * 1e6 / f_tim, which is simply ticks * 1 us with the numbers above. If the pulse period can exceed the counter range, I count update events in the update interrupt and add overflow_count * (ARR + 1) to each capture. On a 16-bit timer at 1 MHz that handling is mandatory for periods above 65 ms. On TIM2 and TIM5, which are 32-bit, the same code path still protects a port to a 16-bit timer.

Two failure modes come up often. The input filter value is in timer clock units, so a value that is too large eats short pulses, while zero lets a noisy edge trigger twice. I start with a small filter and check the shortest expected pulse on a scope. A high time larger than the period, or a zero period, means a missed or glitched capture, and I discard that sample rather than publish it.

Yes No TI1 rising edge Counter resets, CCR1 captured TI1 falling edge, CCR2 captured Channel 2 capture interrupt Read CCR1 and CCR2 together High time <= period? Publish period and pulse width Discard sample, count glitch

If PWM output and capture must run at the same time, I put them on different timers, because PWM input mode takes over the counter reset and channel mapping for its timer.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-29How would you configure a timer-triggered ADC with DMA for fixed-rate sampling at 10 kHz without jitter on a Cortex-M microcontroller?

The 90-second answer

Let the timer decide when sampling happens. A timer update event drives the ADC through its TRGO output in hardware. DMA copies each converted result into a circular RAM buffer. The CPU wakes only on DMA half transfer and transfer complete, then processes the half that is already finished.

That removes the jitter from starting conversion in an ISR. ISR entry, instruction completion and RTOS scheduling all move the sample instant in a software loop. With a hardware trigger, the sample instant is set by the timer counter and the ADC trigger input, neither of which waits for the core.

Assume an STM32G4 running at 170 MHz, sampling at 10 kHz, 12 bit ADC, 256 sample circular buffer. Register names differ on other families, the structure does not.

C
/* TIM3: timer clock is 170 MHz on APB1 with prescaler 1.
   170 MHz / 170 = 1 MHz tick. Update every 100 ticks = 10 kHz. */
TIM_HandleTypeDef htim3 = {0};
htim3.Instance = TIM3;
htim3.Init.Prescaler = 169;
htim3.Init.Period = 99;
htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
htim3.Init.RepetitionCounter = 0;
htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
HAL_TIM_Base_Init(&htim3);

TIM_MasterConfigTypeDef master = {0};
master.MasterOutputTrigger = TIM_TRGO_UPDATE;
master.MasterSlaveMode = TIM_TRIGGERSLAVE_DISABLE;
HAL_TIMEx_MasterConfigSynchronization(&htim3, &master);

/* ADC1: triggered by TIM3 TRGO on the rising edge.
   ADC12 clock configured to 32 MHz in RCC setup for this example. */
ADC_HandleTypeDef hadc1 = {0};
hadc1.Instance = ADC1;
hadc1.Init.Resolution = ADC_RESOLUTION_12B;
hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T3_TRGO;
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_RISING;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.NbrOfConversion = 1;
hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
hadc1.Init.DMAContinuousRequests = ENABLE;
HAL_ADC_Init(&hadc1);

/* DMA1 Channel1: ADC1 to circular buffer, halfword per sample */
DMA_HandleTypeDef hdma_adc = {0};
hdma_adc.Instance = DMA1_Channel1;
hdma_adc.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_adc.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_adc.Init.MemInc = DMA_MINC_ENABLE;
hdma_adc.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
hdma_adc.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
hdma_adc.Init.Mode = DMA_CIRCULAR;
hdma_adc.Init.Priority = DMA_PRIORITY_HIGH;
HAL_DMA_Init(&hdma_adc);
__HAL_LINKDMA(&hadc1, DMA_Handle, hdma_adc);

HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_buf, 256);
HAL_TIM_Base_Start(&htim3);

Enable only the DMA half transfer and transfer complete interrupts. Each handler records which half finished and wakes the consumer. Processing runs in task context.

Timing arithmetic

ItemFigure
Timer tick170 MHz / 170 = 1 MHz, 1 us per tick
Sample period100 ticks = 100 us, so 10 kHz
ADC clock (configured)32 MHz
Sampling time12.5 ADC cycles
SAR conversion, 12 bit12.5 ADC cycles
Total conversion time25 cycles / 32 MHz = 0.78 us
Half buffer time128 samples / 10 kHz = 12.8 ms

Conversion takes 0.78 us of the 100 us period, so the ADC is idle long before the next trigger. If total conversion time reached the period, a trigger would arrive while the ADC was busy and the overrun flag would set. Check that inequality first, including the sampling time for the channel, before choosing the rate.

TIM3 update event 10 kHz ADC1 external trigger DMA circular transfer adc_buf 256 samples HT / TC interrupt Process completed half

Where jitter still creeps in

Clock source sets absolute accuracy. HSI tolerance and drift are far wider than a crystal HSE source, so the 10 kHz rate wanders with temperature and supply. Use HSE or an external clock when the rate is a measurement reference, and state the source in the design notes.

Timer clock derivation is a common trap. On STM32, when the APB prescaler for the bus a timer sits on is not 1, the timer clock is twice that APB clock. Assuming SYSCLK reaches the timer when it does not gives a sample rate off by a factor of two. Read the actual timer clock from the RCC clock configuration report.

Trigger placement also matters. TIM_TRGO_UPDATE fires at counter wrap. TIM_TRGO_OC4 fires at a compare value, which lets you move the sample away from a PWM switching edge on the same timer. That choice changes phase, not rate, and should be recorded.

The remaining failure mode is consumer overrun. If processing of a half takes longer than 12.8 ms, DMA wraps and overwrites data still being read. Toggle a GPIO in the HT and TC handlers and measure the interval on a scope. Check the ADC overrun flag in the ADC error callback. A scope trace shows whether the gap is in sampling or in processing.

Keep the DMA ISR short. Set a volatile completed half index, wake the consumer, return. No blocking calls, no formatting, no mutex waits in that handler.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-30Does averaging many ADC samples remove a fixed offset error, or only random noise?

The 90-second answer

Averaging reduces random noise. It does not remove a fixed offset error. Those are different error types, and only calibration fixes the second one.

Random noise changes from sample to sample, so the mean of N independent samples has noise reduced by sqrt(N). A fixed offset is present in every sample in the same direction, so the mean contains the same offset in full. Averaging 100 samples cuts random noise to one tenth, and leaves a 15 mV offset at 15 mV.

Calibration removes that offset. Apply a known voltage, read the ADC code, and store the difference between the expected code and the actual code. Subtract that offset from every later reading. A two-point calibration also applies a known high voltage and corrects gain error in the same way.

C
// 12-bit ADC, Vref = 3.300 V, checked on Cortex-M4 with GCC 13
#include <stdint.h>

#define ADC_MAX_CODE 4095.0f
#define VREF 3.300f

static float offset_codes;  // measured at a known input voltage

void adc_calibrate_offset(float known_v, uint16_t raw_code)
{
    float expected_code = known_v / VREF * ADC_MAX_CODE;
    offset_codes = (float)raw_code - expected_code;
}

float adc_read_voltage(const uint16_t *samples, int n)
{
    float sum = 0.0f;
    for (int i = 0; i < n; i++) {
        float corrected = (float)samples[i] - offset_codes;
        sum += corrected / ADC_MAX_CODE * VREF;
    }
    return sum / (float)n;
}

Worked numbers

Suppose the specification is plus or minus 5 mV, single-sample noise is 1.6 mV RMS, and the ADC has a fixed offset of 15 mV.

ApproachRandom noise after averagingOffset remainingWorst error
One sample, no calibration1.6 mV RMS15 mVAbout 15 mV plus noise, fails spec
Average 100 samples, no calibration1.6 / sqrt(100) = 0.16 mV RMS15 mVStill about 15 mV, fails spec
Calibrate offset, then average 100 samples0.16 mV RMSNear 0 mV at the calibration temperatureAbout 0.5 mV at 3 sigma, passes spec

The middle row is the trap. The averaged value looks stable on a scope, because the noise is small, and it sits 15 mV away from the true voltage every time.

Where this breaks down

Averaging assumes the samples are independent. Sampling at a fixed rate locked to 50 Hz mains hum puts every sample at the same phase of the hum, so the mean keeps that hum. Sampling over a full mains cycle, or at a rate that is not a multiple of the mains period, spreads the phases and lets the average cancel it.

Averaging also assumes the input is steady during the burst. One hundred samples at 10 kS/s span 10 ms. If the input moves during that window, the mean reports a lagged value. State the window length alongside the noise figure.

Calibration has its own limit. It corrects offset and gain at the temperature and reference voltage used during calibration. An internal bandgap reference on many MCUs drifts with temperature, so the corrected reading drifts with it. An external reference with a stated drift, for example 25 ppm per degree C, bounds that term. Over a 60 degree C range that is 0.15 percent, or about 5 mV at 3.3 V, which already consumes the whole budget in this example.

Apply known voltage Measure raw code Store offset and gain in flash Convert each runtime sample Average N converted samples Noise falls by sqrt of N Offset stays unless calibrated

The rule to repeat: averaging shrinks random noise by sqrt(N), and calibration is what removes a fixed offset.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-31A device sleeps at 8 µA, wakes for 120 ms at 45 mA every 10 s on a 2000 mAh cell: how do you estimate average current, power and battery life, and what makes the real figure worse?

The 90-second answer

Average current is charge per cycle divided by cycle period, not the mean of the two currents. For a periodic wake:

I_avg = D * I_wake + (1 - D) * I_sleep, where D = t_wake / T

With I_sleep = 8 µA, I_wake = 45 mA, t_wake = 120 ms, T = 10 s:

QuantityWorkingResult
Duty cycle D0.120 / 101.2%
Wake contribution0.012 × 45 mA540 µA
Sleep contribution0.988 × 0.008 mA7.9 µA
Average current540 + 7.9548 µA
Average power at 3.7 V0.548 mA × 3.7 V2.03 mW
Ideal life, 2000 mAh2000 / 0.5483649 h = 152 days
Life at 80% usable capacity1600 / 0.548121 days

Sleep current looks negligible here, but it sets the floor. If wake time fell to 10 ms, sleep would be half the budget. Always compute both terms separately before dismissing either.

Why the real device runs shorter

The 152 days assumes the datasheet numbers hold in the product. They rarely do:

  • Wake current is not flat. 45 mA is often a mean over the wake window. Radio TX at +20 dBm, flash erase, sensor warm-up and regulator inrush create 80-150 mA peaks for milliseconds. Charge is what matters, so a peak that doubles current for 20 ms adds as much as the whole nominal wake.
  • Sleep current is measured bare. A typical figure at 25 °C with no peripherals powered can become 15-30 µA once you add a sensor's shutdown current, pull-ups, a regulator's quiescent current, and leakage that roughly doubles every 10-15 °C rise on some CMOS processes. Measure sleep with everything in the shipping configuration, at temperature.
  • Battery capacity is not 2000 mAh in use. Self-discharge of 1-3% per month for Li-ion, capacity loss at 0 °C (often 20% or more), and the cutoff voltage under a 100 mA pulse through aged internal resistance all shrink usable charge. A 2000 mAh cell delivering 548 µA average but 100 mA pulses may hit 3.0 V cutoff long before its coulomb count is spent.
  • Voltage falls over discharge. Average power should use energy, not a fixed 3.7 V. Integrate V(t) * I(t) or use mean voltage weighted by charge. For a coin cell the curve is steep, so the error is larger.
  • Wake time jitters. A retry, a failed sensor read, or a longer radio association stretches t_wake. Use the 95th percentile wake time from logs, not the happy path, and add a margin for retries.

A quick sensitivity check shows where to spend effort:

ChangeNew I_avgIdeal life
Wake 120 ms to 200 ms908 µA92 days
Sleep 8 µA to 30 µA570 µA146 days
Wake current 45 mA to 60 mA728 µA114 days

Wake duration and wake current dominate. Cutting wake time by 40 ms beats chasing sleep current from 8 µA to 2 µA.

Measuring instead of estimating

Put a shunt or coulomb counter (for example an INA219/INA226 or a fuel gauge) in series with the battery, sample fast enough to catch the wake pulse (at least 10 samples per wake), and log for at least 20 cycles. Compute charge per cycle from the integral, then divide by elapsed time. Compare that measured average against the estimate above. A gap points to a specific phase: log current against firmware state markers (GPIO toggles at sleep entry, wake start, wake end) so the extra charge is attributed to a phase, not averaged away.

Python
# Estimator checked against a measured cycle log
def estimate(i_sleep_ua, i_wake_ma, t_wake_s, period_s, capacity_mah, usable=0.8):
    d = t_wake_s / period_s
    i_avg_ma = d * i_wake_ma + (1 - d) * i_sleep_ua / 1000
    life_days = capacity_mah * usable / i_avg_ma / 24
    return i_avg_ma * 1000, life_days  # µA, days

print(estimate(8, 45, 0.120, 10, 2000))  # (548, 121)

State the assumptions with the number: period, wake time at p95, temperature, usable capacity fraction, and mean voltage. Without those, a battery life figure cannot be defended in review.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-32On STM32, how do you choose between Sleep, Stop and Standby for a battery device that must wake on RTC and a GPIO, and what must you configure before entering each mode?

The 90-second answer

Choose the deepest mode that still wakes on every source you need and still keeps the state you need. Sleep keeps everything and wakes on any enabled interrupt, so it is the default when wake latency matters or the source is not listed for Stop. Stop keeps SRAM and registers, stops the main clocks, and wakes on a restricted set of sources, so it fits a battery device that sleeps between RTC ticks or a GPIO edge. Standby loses SRAM and most registers, so it only fits when the current budget forces it and the device can reboot on each wake.

Do not pick from a generic list. The wake tables differ by family and even by part number, so check the reference manual for your exact device before committing.

ModeState keptWake sources to verify for your partWake cost
Sleep, WFISRAM, registers, peripherals as configuredAny unmasked interruptFast, execution resumes where it stopped
StopSRAM and registers, backup domainRTC alarm and wakeup timer, EXTI lines, plus family specific peripherals listed in the manualClocks restart, tens to hundreds of microseconds depending on regulator and clock setup
StandbyBackup domain only, main SRAM lostWKUP pins and RTC alarm or wakeup timerFull boot from reset, milliseconds

RTC and EXTI are the safe examples on STM32F4 and STM32L4. Other Stop wake sources, such as I2C, USART, LPUART, ADC or timers, exist on some families and not others, and some need the peripheral left enabled in a specific state. If a source you need is not in the Stop table for your part, Stop is out, however attractive its current looks.

What to configure before entry

The common failure is entering with the wake flag still set or the interrupt masked in the NVIC. The part wakes at once, the code re-enters, and on a scope it looks as if it never slept.

For Stop, enable the source, clear its flag, unmask it, stop SysTick so it does not wake the part, then enter with WFI. This is STM32F4 HAL, checked against RM0368:

C
HAL_RTC_SetAlarm_IT(&hrtc, &alarm, RTC_ALARMA);
__HAL_RTC_ALARM_CLEAR_FLAG(&hrtc, RTC_FLAG_ALRA);
HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn);

__HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_0);
HAL_NVIC_EnableIRQ(EXTI0_IRQn);

__HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU);
HAL_SuspendTick();
HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);
HAL_ResumeTick();

if (__HAL_RTC_ALARM_CHECK_FLAG(&hrtc, RTC_FLAG_ALRA)) {
    /* RTC wake */
} else if (__HAL_GPIO_EXTI_GET_IT(GPIO_PIN_0)) {
    /* GPIO wake */
}

For Standby, WKUP pins are a separate enable and they stay armed across the reset:

C
HAL_PWR_EnableWakeUpPin(PWR_WAKEUP_PIN1); /* pin depends on the part */
__HAL_PWR_CLEAR_FLAG(PWR_FLAG_SB);
__HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU);
HAL_PWR_EnterSTANDBYMode(); /* does not return */

After the reboot, PWR_FLAG_SB tells boot code that the wake came from Standby rather than power-on, so it can take a short path. A WKUP pin already asserted at entry wakes the part immediately. That is correct for a button to ground with a pull-up, and a loop if the pin is a sensor output already high.

Trade-offs and a worked check

Sleep is not free because it wakes fast. Peripherals left clocked keep drawing current, so measure with the clocks you actually leave on.

Stop keeps your stack and DMA descriptors, which is why it suits a device that wakes, does a short task, and sleeps again. Standby discards them. Anything needed after a Standby wake must be in the backup domain, which is small, or rebuilt from flash. That suits a wake, read, send, sleep cycle. It suits a device with a protocol stack poorly, because you pay full initialisation on every cycle.

Use arithmetic with your own datasheet figures, not a headline number. As a labelled hypothetical, a 2000 mAh cell at 20 uA in Stop lasts about 100,000 hours before self-discharge dominates, while 1 uA in Standby is not 20 times better in practice once the active wake time is included. If each wake runs for 10 ms at 10 mA every 10 s, the active average alone is 10 uA, which swamps the difference between Stop and Standby sleep current. Measure sleep current and wake energy separately, then average them over your real duty cycle.

Before committing, list every wake source, find each one in the Stop and Standby tables for your exact part, and name the flag you will test after wake. If a source is missing, change the mode or move the signal to a pin that is listed.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-33How would you design a watchdog strategy on a FreeRTOS Cortex-M system so a hung task triggers a reset but a slow or busy task does not cause a false reset?

The 90-second answer

Do not let each task feed the hardware watchdog directly. Let every task report progress to one monitor, and let only the monitor feed the watchdog, and only when every critical task has reported inside its own deadline. A hung task then stops reporting, the monitor stops feeding, and the independent watchdog resets the chip. A task that is merely busy, blocked on a queue, or running late but still making progress keeps reporting, so it does not cause a false reset.

On a Cortex-M with FreeRTOS I would use the independent watchdog (IWDG on STM32) rather than the window watchdog for the main reset. On STM32F4 and STM32H7 parts the IWDG is clocked from the LSI oscillator, separate from the HSE and PLL that clock the core, so a main clock failure does not stop it. That is a datasheet specific claim, so I check it for the exact part. If the LSI itself fails, the IWDG can stop too, and for a safety function I would add an external watchdog rather than rely on that. I would add a window watchdog only if I also needed to catch a task spinning too fast, for example a control loop that never blocks.

Sizing the deadlines

The deadline for a task is not its period. It is the longest legitimate gap between progress reports, plus margin for scheduling jitter. If a task blocks on a queue for up to 100 ms, a 20 ms deadline will false-reset it every time the queue is empty.

Worked example, hypothetical but sized the way I size real ones. The monitor runs every 20 ms and the IWDG timeout is 500 ms from the last feed:

TaskPeriodLongest legitimate blockCheckpoint deadlineWorst reset latency after hang
Control (10 ms loop)10 ms5 ms30 ms30 + 20 + 500 = 550 ms
Sensor poll50 ms20 ms I2C wait100 ms100 + 20 + 500 = 620 ms
Comms20 ms80 ms socket timeout150 ms150 + 20 + 500 = 670 ms
Logging100 ms200 ms flash write400 ms400 + 20 + 500 = 920 ms

The worst case is the logging task at about 920 ms. The timeout does not start when the task hangs. It starts at the last feed, which can be up to one monitor period before the monitor notices the miss. That gap is deliberate. It lets a task recover from a transient stall, such as a flash write that overruns once, without a reset, while a truly hung task still resets within about 1 s. If 920 ms is too slow for the application, I shorten the logging deadline or the IWDG timeout, and I accept the higher false reset risk that comes with it.

C
/* Checked against FreeRTOS 11 on Cortex-M4, STM32 IWDG */
#define NUM_CRITICAL 4
static volatile uint32_t last_progress[NUM_CRITICAL];
static const uint32_t deadline_ms[NUM_CRITICAL] = {30, 100, 150, 400};

void task_checkpoint(int id) {
    last_progress[id] = xTaskGetTickCount();
}

void watchdog_monitor(void *arg) {
    for (;;) {
        uint32_t now = xTaskGetTickCount();
        bool healthy = true;
        for (int i = 0; i < NUM_CRITICAL; i++) {
            if ((now - last_progress[i]) > pdMS_TO_TICKS(deadline_ms[i])) {
                healthy = false;
                log_watchdog_miss(i, now - last_progress[i]);
            }
        }
        if (healthy) {
            IWDG_Refresh(); /* only place that feeds it */
        }
        vTaskDelay(pdMS_TO_TICKS(20));
    }
}

Each task calls task_checkpoint() after it completes a unit of real work, not at the top of its loop. A task stuck inside a driver call never reaches the checkpoint. A task spinning in a tight loop without doing work also never reaches it, which is the point.

All inside deadline Any miss Task completes work Update last_progress Monitor checks every 20 ms Feed IWDG Log task id and gap Stop feeding IWDG expires 500 ms after last feed Reset and record cause

Failure modes I check for

Feeding the watchdog from a timer ISR is the classic mistake. The ISR keeps firing even when all tasks are dead, so the watchdog never expires. The same applies if the monitor itself is the hung task. I give the monitor a high priority, keep it short, and never let it block on a mutex or queue. If the monitor hangs, nothing feeds the IWDG.

A second failure mode is a shared clock or supply. The IWDG on the parts above survives a main clock failure because it uses the LSI, but it does not survive an LSI failure or a supply collapse that stops the LSI. I check the reset cause register (for example RCC_CSR on STM32) after boot, then copy the cause and the last missed task id into a retained backup register or a flash fault log before clearing it. Without that record, a field reset tells you nothing.

A third mode is priority starvation. If a low-priority sensor task is starved by a runaway high-priority task, its checkpoint goes stale and the monitor correctly stops feeding. The reset is not false in that case, but the log will blame the sensor task. I therefore log the monitor's own run count and the current highest priority ready task, so the post-mortem shows whether the victim was starved rather than hung.

Finally, I test it by suspending each task in turn with vTaskSuspend() and confirming the reset happens within the worst case latency for that task, about 920 ms for logging and less for the others, and by injecting a 250 ms block into the logging task and confirming no reset occurs. If either test fails, the deadlines are wrong, not the watchdog.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-34How does brown-out detection protect saved configuration when power is lost?

The 90-second answer

Brown-out detection watches the supply rail and fires before the MCU drops below its minimum operating voltage. That early warning is the only window you get to save configuration. Without it, the core keeps running while flash writes become unreliable, RAM contents corrupt, and a half-written config page is what you boot from next time.

On STM32 parts this is the PVD (programmable voltage detector) or the dedicated BOD circuit, depending on the family. You set the threshold above the lowest voltage at which flash programming is still guaranteed, for example 2.9 V on a 3.3 V rail with a 2.7 V minimum. When VDD crosses down through that threshold, the hardware raises an interrupt. In that interrupt you only set a flag and return. The main loop, or a high-priority task, then saves state while the rail is still healthy. Masking all interrupts in the ISR would block that save path, so do not do it.

VDD falling PVD/BOD threshold crossed Interrupt: set save flag and return Main loop saves config to alternate slot with CRC Verify read-back Enter reset / stop CPU Next boot: pick newest slot with valid CRC

What gets saved, and how

Save only what must survive: calibration constants, user settings, a boot counter, and a flag saying an update was in progress. Keep the record small and fixed size. A typical record is a struct with a sequence number, the config, and a CRC32 over the sequence number and config.

Write it to one of two slots, never over the only valid copy. Alternate slots on each save. On boot, read both, check CRC, and use the one with the higher sequence number. If the newest fails CRC, fall back to the older one. That is what protects you when power dies mid-write: the slot being written is incomplete, the other slot is still intact.

C
// Checked against STM32F4 HAL style, simplified. Save routine must run from RAM.
volatile bool bod_pending = false;

void PVD_IRQHandler(void) {
    bod_pending = true;   // do not write flash in the ISR
}

void save_config(const config_t *cfg) {
    static uint32_t seq = 0;
    slot_t rec;
    rec.seq = ++seq;
    rec.cfg = *cfg;
    rec.crc = crc32((const uint8_t *)&rec.seq, sizeof(rec.seq) + sizeof(rec.cfg));
    int slot = (int)(seq & 1);
    flash_write_slot(slot, &rec);
    slot_t back;
    flash_read_slot(slot, &back);
    if (back.seq == rec.seq &&
        back.crc == crc32((const uint8_t *)&back.seq, sizeof(back.seq) + sizeof(back.cfg))) {
        // verified, safe to halt
    }
    while (1) { __WFI(); }  // wait for reset, rail is collapsing
}

int main(void) {
    // ... init ...
    for (;;) {
        if (bod_pending) {
            save_config(&current_config);
        }
        // normal work
    }
}

The timing budget decides if it works

The detector only helps if you can finish the write before the rail falls below the flash minimum. That time comes from the bulk capacitance on the rail. Hypothetical example: 470 uF of hold-up, load of 20 mA, rail falling from 3.3 V to 2.7 V.

QuantityValue
Hold-up timeC x deltaV / I = 470e-6 x 0.6 / 0.02 = 14 ms
Flash page write (typical internal flash)5 to 10 ms
Margin left for CRC and read-back4 to 9 ms

That fits, but only just. If your page write takes 25 ms, or your load is 80 mA, the same capacitor gives you 3.5 ms and the save fails. Then you need a bigger capacitor, a smaller record that fits in one page, or a different store such as FRAM or EEPROM with a faster write and lower current.

Failure modes to name in the interview

Threshold set too low: the interrupt fires after flash programming is already out of spec, so writes silently corrupt. Threshold set too high: normal load transients trip it and the device resets constantly. Saving on every config change wears flash, datasheets for common STM32 families list endurance in the range of 10k to 100k program/erase cycles per sector depending on the family, so batch changes or use FRAM for frequently changing values. Writing flash from code executing in the same flash bank: on many STM32 parts the CPU cannot fetch instructions from the bank being programmed, so the save routine and its call chain must run from RAM, and interrupts that vector through flash need care during the write.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-35A legacy parser uses malloc, pointer arithmetic and side-effect expressions and must be made MISRA C compliant within a fixed 512-byte RAM budget without changing its wire format: how do you refactor it and prove the bound?

The 90-second answer

I would not try to make the original code compliant line by line. I would replace its three hazards together, because they interact. A variable length frame parsed with pointer arithmetic, stored in a heap block, and built with side effect expressions can overrun the heap block, form an out of bounds pointer, and evaluate in a different order on the next compiler. Fixing only the checker warnings leaves that behaviour intact.

My constraints, stated before I touch code, are: no heap in the safety path, no change to the wire format, total static RAM for parser buffers at or below 512 bytes, and no MISRA deviation for the parser itself. If the vendor driver behind it still allocates, that is a separate deviation with its own test. The parser gets a fixed pool, indexed access with explicit length checks, and one side effect per statement.

Sizing the pool, with arithmetic

The wire format is a one byte length, then that many payload bytes, maximum payload 96 bytes. The old code called malloc(len + 1) per frame. Three frames can be live at once: one being received, one queued for the consumer, one held during a retry. Worst case live storage is therefore 3 times 97, which is 291 bytes, not 512. I allocate a single static array of 384 bytes and split it into three fixed slots of 128 bytes each. The extra 31 bytes per slot cover alignment and a guard byte I never expose. Fixed slots waste space when frames are short, and that waste is the point. It makes exhaustion predictable and fragmentation impossible.

C
#define SLOT_COUNT (3u)
#define SLOT_SIZE  (128u)
#define MAX_PAYLOAD (96u)

typedef struct
{
    uint8_t len;
    uint8_t data[MAX_PAYLOAD];
} frame_t;

static frame_t slots[SLOT_COUNT];
static uint8_t slot_used[SLOT_COUNT];
static uint8_t high_water;

_Static_assert(sizeof(frame_t) <= SLOT_SIZE, "frame exceeds slot");

sizeof(frame_t) is 97 on the target, so the assertion holds with margin. If a future format change pushes payload past 96, the build fails instead of corrupting the next slot at runtime. I also track high_water, the largest number of slots ever in use, and read it in test. If it reaches 3 in normal operation, the design assumption is wrong and I revisit the queue depth rather than enlarging the pool blindly.

Allocation becomes a search over a fixed set, with a defined failure. When all three slots are in use, the parser drops the newest frame, increments a diagnostic counter, and returns an error to the caller. It does not block, retry, or fall back to malloc. Dropping is safe here because the sender retransmits and the consumer treats a missing sequence number as a gap. In a different system where dropping a frame would lose a safety command, the correct answer would be to size for the true worst case or to stop the sender, and I would say so in the design note.

Pointers and bounds

The original parser advanced two pointers through the received buffer. That violates Rule 18.4, which bans pointer arithmetic, and it hides the bound check. I keep the buffer as an array plus a length, and I index it. Rule 18.1 still applies to the one place a pointer is unavoidable, the buffer handed to the UART driver, so I check that pointer for null and I never form a pointer past the end of the array.

C
/* Non-compliant pattern: pointer arithmetic, unchecked length */
uint8_t *p = rx_buf;
uint8_t len = *p++;
while (len-- > 0u) { *dst++ = *p++; } /* overruns if len exceeds buffer */

/* Compliant version */
static uint8_t parse_frame(const uint8_t *buf, uint8_t buf_len)
{
    uint8_t status = 1u; /* 1 = error */
    uint8_t i;
    uint8_t slot = find_free_slot();
    if ((buf != NULL) && (buf_len >= 1u) && (slot < SLOT_COUNT))
    {
        uint8_t len = buf[0];
        if ((len <= MAX_PAYLOAD) && ((uint8_t)(len + 1u) <= buf_len))
        {
            for (i = 0u; i < len; i++)
            {
                slots[slot].data[i] = buf[(uint8_t)(i + 1u)];
            }
            slots[slot].len = len;
            slot_used[slot] = 1u;
            status = 0u;
        }
    }
    return status;
}

The subtle failure is the length byte itself. A corrupted or malicious frame can claim 200 payload bytes in a 97 byte buffer. The old code trusted it and wrote past the heap block, which on a microcontroller overwrites adjacent static data with no fault raised. The new code rejects the frame before any copy, and the test suite feeds it lengths of 0, 96, 97 and 255 against buffers of 1, 97 and 128 bytes. I also avoid casting away const to satisfy a driver that wants a writable pointer, per Rule 11.8. I copy into a writable slot instead. That copy costs a few cycles, and I can state the cost: at most 96 byte copies per frame, bounded, with no loop whose trip count comes from untrusted data without a prior check.

Side effects

The original code built frames with expressions such as dst[i++] = src[j++] + (x = next()). That breaks Rule 13.2, because the value of the expression and its side effects are not the same between sequence points, and the order of evaluation of operands is unspecified in C. One compiler may increment i before reading j, another may not, and optimisation can change the result again. I rewrite every such expression into separate statements.

C
/* Non-compliant: Rule 13.2, multiple side effects, unspecified order */
slots[s].data[i++] = buf[j++] + (uint8_t)next_seq();

/* Compliant: one side effect per statement, order explicit */
uint8_t seq = next_seq();
uint8_t payload = buf[j];
slots[s].data[i] = (uint8_t)(payload + seq);
i = (uint8_t)(i + 1u);
j = (uint8_t)(j + 1u);

I apply the same rule to controlling expressions. Rule 13.3 bans assignment inside if and while, so if ((c = read()) != 0) becomes a read into a variable followed by a comparison. I also keep the for loop counter untouched in the body, per Rule 14.2. A MISRA checker flags most of these, but I do not trust it alone for Rule 13.2. I compile the same module at -O0 and -O2 and run the frame tests under both. If results differ, there is still an unspecified order somewhere, and the checker missed it.

What I hand over

The change is reviewed against a short trace table, not just a clean checker report.

InputOld behaviourNew behaviour
len 10, buffer 11 bytescopies 10 bytes, heap block sized by callercopies 10 bytes into slot, slot marked used
len 200, buffer 97 byteswrites past heap block, corrupts adjacent static datarejected, error returned, no copy
all 3 slots in usemalloc may return null or fragment the heapnewest frame dropped, counter incremented
len 0loop runs zero times, empty frame storedaccepted as empty frame, length stored as 0

That table, the static assertion, the high water mark, and the two optimisation level test runs are the evidence. A clean MISRA report alone would not convince me, and it should not convince an auditor either.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-36How would you implement a PID loop in fixed point on a Cortex-M0 without an FPU, and how would you choose the scaling and guard against overflow and integral windup?

The 90-second answer

Pick integer formats from the ranges you actually need, do every multiply in 64 bits, and clamp the integral and the output before they can wrap. On a Cortex-M0 there is no FPU, so the loop is scaled integer arithmetic with a known sample period.

Say the loop runs at 1 kHz, the error is in milli-units (for example, temperature x1000 or speed in rpm x10), and the output is a PWM duty from 0 to 1000. I would store error, measurement and integral as int32_t in that scaled unit, and store gains as Q8.8 or Q16.16 depending on whether a gain can exceed 1.0 by much. Q8.8 gives a gain step of 1/256 and fits a gain up to 127.99 in 16 bits. Q16.16 gives finer steps and a gain up to 32767, at the cost of needing 64-bit intermediates for every product. On an M0 a 64-bit multiply is a library call, so I keep the number of multiplies per tick small: three for P, I and D.

The integral is the dangerous term. It accumulates every tick, so without a clamp it will wind up while the actuator is saturated and then take just as long to unwind. I clamp the integral to a range derived from the output limits. With ki in Q8.8, an integral term that alone should not exceed the output range gives i_max = out_max * 256 / ki_q8. For out_max 1000 and ki_q8 3, that is about 85333. The output itself is clamped in 64 bits before any cast to int32_t.

C
// Checked against GCC 12 for Cortex-M0, -O2. Gains in Q8.8.
// error, integral, output in milli-units / per-mille duty.
typedef struct {
    int32_t kp_q8, ki_q8, kd_q8;  // Q8.8
    int32_t integral;             // milli-units * ticks, clamped
    int32_t prev_meas;
    int32_t i_min, i_max;         // integral clamp
    int32_t out_min, out_max;     // 0..1000
} pid_t;

static int32_t clamp32(int32_t v, int32_t lo, int32_t hi) {
    return v < lo ? lo : (v > hi ? hi : v);
}

static int64_t clamp64(int64_t v, int64_t lo, int64_t hi) {
    return v < lo ? lo : (v > hi ? hi : v);
}

int32_t pid_step(pid_t *p, int32_t setpoint, int32_t meas) {
    int32_t err = setpoint - meas;
    int64_t prop = (int64_t)err * p->kp_q8 >> 8;
    int64_t deriv = (int64_t)(p->prev_meas - meas) * p->kd_q8 >> 8;
    p->prev_meas = meas;

    p->integral = clamp32(p->integral + err, p->i_min, p->i_max);
    int64_t integ = (int64_t)p->integral * p->ki_q8 >> 8;
    int64_t out = prop + integ + deriv;

    int64_t out_c = clamp64(out, p->out_min, p->out_max);
    return (int32_t)out_c;
}

Two choices decide whether this works. First, the derivative acts on measurement, not on error, so a setpoint step does not produce a derivative kick. Second, the derivative term is usually noisy from an ADC, so in practice I filter it or compute it over several ticks rather than trusting one sample. Also, dt is folded into ki and kd at build time for a fixed 1 kHz tick. If the tick period changes, the gains are wrong, so the tick comes from a timer compare and the loop asserts on a missed deadline instead of silently running at the wrong rate.

FormatResolutionRange for gainCost on M0
Q8.8 in int16_t0.00390 to 127.9932-bit multiply after widening
Q16.16 in int32_t0.0000150 to 3276764-bit multiply per term
Q4.12 in int16_t0.000240 to 7.99cheap, but coarse for small gains

A worked trace shows the clamps doing their job. Hypothetical figures: setpoint 1000, measurement starts at 0, kp_q8 = 128 (0.5), ki_q8 = 3 (about 0.012 per tick), kd_q8 = 0, integral clamp +/-85333, output 0 to 1000. Each integral term below is integral * 3 >> 8.

TickMeasErrorIntegral after stepIntegral termRaw outputReturned
101000100011500 + 11 = 511511
2200800180021400 + 21 = 421421
3600400220025200 + 25 = 225225
49505022502625 + 26 = 5151
51100-100215025-50 + 25 = -250

At tick 5 the raw output goes negative, the returned value clamps to 0, and the integral still decreases because the error is negative. That is the behaviour I want: the integral unwinds while the output sits at the limit, instead of staying wound up from earlier ticks. The integral clamp alone does not stop all windup, since the integral can sit at i_max while saturated, but it bounds how far it can go and how long unwinding takes.

Overflow is handled by construction, not by hope. The largest product is err (bounded by the sensor range, say +/-100000 milli-units) times a Q8.8 gain (bounded by 32767). That product fits in 64 bits with room to spare, and the shift brings it back to the output scale before it is added to the other terms. The sum stays in int64_t and is clamped in that domain, so the cast to int32_t on return cannot overflow. I check those bounds with the actual sensor and actuator ranges for the product, and I add a debug build that asserts if err or the integral ever reaches the clamp, since reaching it in normal operation means the gains or the clamp are wrong.

If the loop later moves to a Cortex-M4 with an FPU, the same structure survives: keep the clamps, keep derivative on measurement, and only swap the arithmetic. The scaling decisions stay, because they come from the plant and the actuator limits, not from the core.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-37How would you frame a sensor reading with a CRC-16 and a length byte on a Cortex-M, and what does the receiver do when the CRC fails?

The 90-second answer

I would send a fixed header, a length byte, the payload, and a CRC-16 computed over the header and payload. The receiver buffers bytes until it has a complete frame, checks the CRC, and only then hands the payload to the application. If the CRC fails, it drops the frame, counts the error, and waits for the next sync byte. The sender resends when it does not get an ACK for that sequence number.

A frame for a sensor node talking to a host over UART at 115200 baud:

FieldSizeValue
Sync1 byte0xA5
Length1 bytePayload length, 0 to 64
Type1 byteMessage type, for example 0x01 for a sensor report
Seq1 byteSequence number, wraps at 255
Payload0 to 64 bytesApplication data
CRC-162 bytesLittle-endian, over Length through Payload

The sync byte can also occur inside a payload, so the receiver cannot treat every 0xA5 as a new frame. I escape it on the wire: 0xA5 becomes 0x7D 0x25 and 0x7D becomes 0x7D 0x5D. That keeps framing unambiguous and lets the parser resynchronise by scanning for the next unescaped sync byte.

For the CRC I use CRC-16/CCITT-FALSE, polynomial 0x1021, initial value 0xFFFF. It detects all single-bit and double-bit errors, all odd numbers of bit errors, and all burst errors up to 16 bits. On a 32-byte payload the cost is 2 bytes, about 6 percent overhead.

C
#include <stdint.h>
#include <stddef.h>

static uint16_t crc16_ccitt(const uint8_t *data, size_t len)
{
    uint16_t crc = 0xFFFFu;
    for (size_t i = 0; i < len; i++) {
        crc ^= (uint16_t)data[i] << 8;
        for (int bit = 0; bit < 8; bit++) {
            crc = (crc & 0x8000u) ? (uint16_t)((crc << 1) ^ 0x1021u)
                                 : (uint16_t)(crc << 1);
        }
    }
    return crc;
}

#define MAX_PAYLOAD 64u

typedef struct {
    uint8_t state; /* 0 = hunt for sync, 1 = collect frame */
    uint8_t len;
    uint8_t buf[1 + 1 + 1 + MAX_PAYLOAD + 2];
    uint8_t idx;
    uint32_t crc_errors;
} parser_t;

/* Returns 1 when a complete, CRC-valid frame has been decoded. */
int parser_feed(parser_t *p, uint8_t byte, uint8_t *type, uint8_t *seq,
                uint8_t *payload, uint8_t *payload_len)
{
    if (p->state == 0) {
        if (byte == 0xA5u) {
            p->state = 1;
            p->idx = 0;
        }
        return 0;
    }
    p->buf[p->idx++] = byte;
    if (p->idx == 1) {
        p->len = byte;
        if (p->len > MAX_PAYLOAD) {
            p->state = 0; /* Bad length: drop and resync at once. */
            return 0;
        }
    }
    uint8_t total = (uint8_t)(1 + 1 + 1 + p->len + 2);
    if (p->idx < total) {
        return 0;
    }
    uint16_t received = (uint16_t)(p->buf[total - 2] | ((uint16_t)p->buf[total - 1] << 8));
    uint16_t computed = crc16_ccitt(p->buf, (size_t)(total - 2));
    p->state = 0;
    if (received != computed) {
        p->crc_errors++;
        return 0;
    }
    *type = p->buf[1];
    *seq = p->buf[2];
    for (uint8_t i = 0; i < p->len; i++) {
        payload[i] = p->buf[3 + i];
    }
    *payload_len = p->len;
    return 1;
}

The length check matters before the CRC. If a corrupted length says 200, the parser would otherwise wait for 200 bytes and swallow the next valid frame. Rejecting any length above 64 drops the frame immediately and bounds the static buffer, which protects RAM on a small MCU.

Recovery trace

Suppose a report with payload 10 20 30 40 arrives with the third byte flipped to 31:

StepReceiver actionResult
1Sync found, length 4 acceptedCollecting frame
29 bytes collectedCRC computed over header and payload
3Computed CRC differs from received CRCFrame dropped, crc_errors increments
4No ACK sent for that sequence numberSender times out after 50 ms and resends
5Next sync byte foundParser resynchronises, next frame parsed normally

The sender keeps the last few frames and resends on timeout or on a NACK that names the missing sequence number. The receiver discards a duplicate sequence number after a resend, so a retransmit cannot deliver the same reading twice to the application.

A corrupted sync byte loses that one frame, because the parser stays in hunt state until the next sync. That is the safe outcome. At 115200 baud a 70-byte frame takes about 6 ms, so resync latency is bounded by one frame time. A CRC catches line noise, not deliberate forgery, so I would not rely on it alone for commands that change device state.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-38How do you configure CAN bit timing, and how do you handle error frames and bus-off recovery in firmware?

The 90-second answer

CAN bit timing is set once from the CAN clock, and every node must use the same nominal bit rate and a compatible sample point. A bit is divided into time quanta. One TQ is the CAN clock divided by the prescaler. Bit time is SyncSeg (1 TQ) plus BS1 plus BS2. The sample point is after SyncSeg plus BS1.

Example: STM32F4, CAN clock 42 MHz from APB1 (the F4 APB1 limit), 500 kbit/s. Bit time is 2 µs. Use 12 TQ per bit. TQ is 166.7 ns, TQ clock is 6 MHz, prescaler is 7. Set BS1 to 8 TQ and BS2 to 3 TQ. Sample point is (1 + 8) / 12 = 75%. Set SJW to 2 TQ, no larger than BS2. Another node can use a different prescaler if the bit rate matches and its sample point is within a few percent. If the bit rate differs, no frame decodes.

C
/* STM32F4 CAN1, 42 MHz APB1 clock, 500 kbit/s, 12 TQ/bit */
CAN_InitTypeDef can = {0};
can.Prescaler = 7;          /* 42 MHz / 7 = 6 MHz, TQ = 166.7 ns */
can.Mode = CAN_MODE_NORMAL;
can.SyncJumpWidth = CAN_SJW_2TQ;
can.TimeSeg1 = CAN_BS1_8TQ;
can.TimeSeg2 = CAN_BS2_3TQ;
can.AutoBusOff = DISABLE;   /* manual recovery, see below */
can.AutoRetransmission = DISABLE;
can.ReceiveFifoLocked = DISABLE;
can.TransmitFifoPriority = DISABLE;
HAL_CAN_Init(&hcan1, &can);

Error frames and bus-off are handled by the controller hardware first, and by firmware policy second. The controller raises an error frame on a stuff error, CRC error, form error, ACK error or overload condition. An error-active node sends 6 dominant bits. An error-passive node sends 6 recessive bits, which other nodes may not see as an error frame.

Controller stateCounter ruleWhat the node does
Error activeTEC and REC at or below 127Sends active error frames, takes part normally
Error passiveTEC above 127, or REC above 127Sends passive error frames, adds delay before retransmission
Bus offTEC above 255Stops transmitting and receiving, leaves the bus

Bus-off recovery in the CAN specification is 128 occurrences of 11 consecutive recessive bits, after which the node resets its error counters and becomes error active again. Firmware should not fight that sequence. On a bus-off interrupt, stop new transmit requests, flush pending mailboxes, record the TEC value and a timestamp, then wait for the controller to complete recovery or reinitialise it. STM32 CAN has an AutoBusOff option that does the 128 sequence in hardware. I leave it disabled in safety related firmware so the driver can apply backoff: first retry after 100 ms, then 500 ms, then 2 s, and raise a diagnostic fault if bus-off repeats more than 5 times in 10 s. A node that reinitialises instantly and retries a frame that caused the fault will drive the bus off again.

Error and status interrupts arrive on the CAN1_SCE interrupt, not on the receive FIFO interrupt.

C
void CAN1_SCE_IRQHandler(void) { HAL_CAN_IRQHandler(&hcan1); }

void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan) {
    uint32_t err = HAL_CAN_GetError(hcan);
    if (err & HAL_CAN_ERROR_BOFF) {
        HAL_CAN_Stop(hcan);
        HAL_CAN_AbortTxRequest(hcan, CAN_TX_MAILBOX0 | CAN_TX_MAILBOX1 | CAN_TX_MAILBOX2);
        busoff_count++;
        busoff_deadline = tick_ms + backoff_ms(busoff_count);
        diag_set(DIAG_CAN_BUSOFF);
    } else if (err & HAL_CAN_ERROR_EPV) {
        diag_set(DIAG_CAN_PASSIVE);
    }
}

The main loop checks busoff_deadline, calls HAL_CAN_Start() only after it expires, and clears the diagnostic only after 1 s of clean traffic. That gives the rest of the bus time to recover and stops a faulty node from flooding the bus with error frames.

No Yes Yes No Bus-off interrupt Stop TX and flush mailboxes Log TEC and timestamp Backoff expired? Restart CAN controller Frames clean for 1 s? Clear diagnostic Increment backoff and repeat

Two failure modes come up in review. First, mismatched sample points on long cables or at 1 Mbit/s, where propagation delay eats into BS1. The fix is to move the sample point later and shorten the cable or add proper termination, 120 ohms at each physical end, not at every node. Second, a transmit mailbox stuck retrying a frame for a node that has left the bus. Disabling auto retransmission and aborting mailboxes on bus-off prevents that frame from blocking newer diagnostics.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-39How do you handle a CAN transmit queue shared by tasks of different urgency without starving safety frames?

The 90-second answer

Do not let tasks write straight into a FIFO queue or into the CAN controller's mailboxes. Put one dispatcher between the tasks and the controller, keep a software priority queue sorted by CAN identifier and deadline, and present only the winner to a single transmit mailbox. CAN arbitration only chooses among frames the controller is actually offering at that moment. If three low-priority telemetry frames already occupy the mailboxes, a safety frame queued in software never reaches arbitration, however urgent its ID is.

I would split producers by class, not by task priority alone. Safety frames (brake, steering, fault) get the lowest IDs, a short deadline, and a reserved path. Control frames come next. Telemetry and diagnostics get the highest IDs and are the first dropped. Each queued item carries its ID, deadline in ticks, and a sequence or generation so a stale periodic frame can be replaced instead of sent late.

C
typedef struct {
    uint32_t id;          /* lower = higher CAN priority */
    uint32_t deadline;    /* tick when it becomes useless */
    uint8_t  len;
    uint8_t  data[8];
    uint8_t  is_safety;
} can_msg_t;

/* Called from task context. Non-blocking by design. */
bool can_submit(const can_msg_t *m)
{
    if (xQueueSendToFront(tx_queue, m, 0) != pdPASS) {
        can_drop_count++;
        return false;  /* caller must not block or retry in a loop */
    }
    return true;
}

In practice I would not use a plain FreeRTOS queue as the priority structure. I would use three queues (safety, control, telemetry) or a small sorted array protected by a critical section, because a single FIFO reintroduces head-of-line blocking inside the queue itself. The dispatcher task, at a priority above telemetry producers but below the safety producer, pops in class order, discards anything past its deadline, and loads the one mailbox. Reserving a separate safety queue also means a full telemetry queue can never make can_submit fail for a safety frame.

Why the naive designs starve safety frames

DesignWhat happensFailure you see on the bus
Shared FIFO queueA burst of 20 telemetry frames queued at t=0 sits ahead of a safety frame queued at t=1 msSafety latency = 20 frame times, unbounded if producers keep filling the queue
Direct mailbox writes from each taskEach task grabs a free mailbox, low-priority task wins the raceController offers only low IDs to arbitration, safety frame waits in a task-local buffer
Priority queue, 3 mailboxes filledDispatcher loads all mailboxes with whatever was queued firstSame problem one level down, plus a stale frame in a mailbox cannot always be withdrawn cleanly
Priority queue, 1 mailbox, abort on preemptionSafety frame replaces a pending low frameCorrect, but abort on some STM32 CAN / FDCAN peripherals needs a request plus confirmation, and the aborted frame may already be in arbitration

The last row is the one I would ship, with the abort path exercised in test. On controllers where abort is unreliable, the single mailbox still bounds the damage: at most one low-priority frame is in flight ahead of the safety frame, instead of three or twenty.

Worked latency check

Assume classic CAN at 500 kbit/s, 8-byte data frames, worst case about 130 bits including stuff bits and interframe space. That is roughly 260 microseconds per frame on the wire. If the dispatcher holds one mailbox and the queue is priority ordered, worst case safety latency is one frame already in transmission plus the safety frame itself: about 520 microseconds, plus task wakeup time. With three mailboxes pre-filled with telemetry, the same calculation gives about 780 microseconds before the safety frame is even offered, and that assumes the queue stops growing. At 250 kbit/s every figure doubles, which is why I would recheck the deadline against the actual bit rate rather than trusting a rule of thumb.

Bus load matters as much as queue order. Once the safety frame is offered, CAN arbitration guarantees it wins against any higher ID, so it can only be delayed by a frame already transmitting or by another frame with an even lower ID. High bus load still hurts because it lengthens the queueing delay before the frame is offered and increases the chance that a lower-ID frame starts just ahead of it. I would keep total worst-case load under about 50% for a safety path, measure it with the controller's bus-off and error counters, and move bulk telemetry to a slower rate or a separate segment before touching queue code.

Aging, replacement, and drop policy

Periodic frames should overwrite, not accumulate. If a task produces a wheel-speed frame every 10 ms and the queue still holds the one from 25 ms ago, sending it wastes bus time and delivers stale data. I would keep one slot per periodic ID and replace its payload in place. Event frames (fault reports) are queued, but with a deadline: the dispatcher drops anything whose deadline has passed and increments a counter, because a late fault frame that displaces a fresh safety frame is worse than no frame.

Aging is a safety net, not the main mechanism. If a control frame has waited more than, say, 5 ms, promote it above fresh telemetry. Without aging, a continuous telemetry stream cannot starve a priority queue (priority order prevents that), but a stream of safety frames can starve control frames indefinitely, and that shows up as a control loop missing its deadline. The promotion threshold should come from the control loop's period, not from a guess.

Failure modes I would test for

A producer that blocks on a full queue while holding a mutex creates priority inversion that no queue ordering fixes, so can_submit must be non-blocking and the drop counter must be visible in diagnostics. A dispatcher that runs at the same priority as a flooding telemetry task can itself be starved by the RTOS scheduler, so it needs a priority above all producers except the safety producer, and the safety producer should use SendToFront or its own queue. Finally, CAN error frames and bus-off states stall the mailbox: the dispatcher must timeout on a mailbox that never completes, count consecutive failures, and stop feeding the queue rather than letting it grow without bound while the bus is down.

Safety Control Telemetry Yes No Task produces frame Class Safety queue Control queue Telemetry queue Dispatcher Deadline passed? Drop and count Load single mailbox CAN arbitration by ID

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-40How would you use the Cortex-M MPU to make a wild write to a peripheral register fault instead of silently changing hardware?

The 90-second answer

I would leave the peripheral space denied by default and grant access only to the one register block the driver owns. On Cortex-M that is two MPU regions. Region 0 denies the peripheral space, region 1 allows, say, GPIOA. A wild pointer write to any other peripheral, or to a peripheral address with no grant, then raises a MemManage fault. The fault gives me the address and the stacked PC, so I can log it and reset instead of letting the write change hardware state silently.

The MPU checks the address against the regions and the access type against the region permissions. It does not check whether a pointer is logically correct. So the protection is only as narrow as the region I grant. Granting all of GPIOA catches a wild write to a timer or UART register, but not a wild write to the wrong GPIO register inside GPIOA. That is the main limit to state up front.

Setup on Cortex-M4

Regions must be a power-of-two size and aligned to that size. GPIOA on an STM32F4 sits at 0x40020000, so a 1 KB region fits cleanly. The peripheral space starts at 0x40000000 and a 256 MB region covers 0x40000000 to 0x4FFFFFFF.

C
/* Checked against CMSIS core_cm4.h, Cortex-M4 */
#include "core_cm4.h"

#define GPIOA_BASE 0x40020000UL

static void mpu_init(void)
{
    ARM_MPU_Disable();

    /* Region 0: no access to the peripheral space, no execute */
    ARM_MPU_Region_t deny = {
        .RBAR = ARM_MPU_RBAR(0x40000000UL, 0, 0, 0, 0),
        .RASR = ARM_MPU_RASR(ARM_MPU_AP_NONE, 0, 0, 0,
                             ARM_MPU_TEX_LEVEL0, 0, 1, ARM_MPU_SIZE_256MB)
    };
    ARM_MPU_SetRegion(0, &deny);

    /* Region 1: GPIOA only, privileged read/write, device memory, no execute */
    ARM_MPU_Region_t gpioa = {
        .RBAR = ARM_MPU_RBAR(GPIOA_BASE, 0, 0, 0, 0),
        .RASR = ARM_MPU_RASR(ARM_MPU_AP_RW, 0, 0, 0,
                             ARM_MPU_TEX_LEVEL0, 0, 1, ARM_MPU_SIZE_1KB)
    };
    ARM_MPU_SetRegion(1, &gpioa);

    ARM_MPU_Enable(MPU_CTRL_PRIVDEFENA_Msk);
}

PRIVDEFENA keeps the default map for privileged code outside the regions, so flash and RAM keep working. The explicit regions override it where they match. Without that bit, privileged accesses with no matching region would fault and break normal code.

If the driver runs unprivileged, as in a FreeRTOS task with MPU support, I would use ARM_MPU_AP_RO or ARM_MPU_AP_NONE for the deny region and grant the task only the region it needs. Then even a privileged-only check is not the issue, because the task itself has no right to the other peripherals.

What the fault looks like

A denied write raises MemManage, provided that fault is enabled in SCB->SHCSR. The handler reads the cause and the faulting address.

FieldExample valueMeaning
SCB->CFSR.MEMACCERR1Access violation
SCB->CFSR.MMARVALID1SCB->MMAR is valid
SCB->MMAR0x40021000Address of the denied write, for example a timer register
Stacked PCaddress in the writing taskInstruction that issued the store
C
void MemManage_Handler(void)
{
    uint32_t cfsr = SCB->CFSR;
    uint32_t mmar = SCB->MMAR;
    uint32_t *stk = (uint32_t *)__get_MSP();
    uint32_t pc = stk[6];
    log_fault(cfsr, mmar, pc);
    NVIC_SystemReset();
}

Reset is the default response. The write may have reached the bus before the fault on some parts, and the hardware state is unknown. Continuing usually just hides the bug until it shows up as a wrong output. In an RTOS I might suspend the faulting task instead, but only if the system can run safely without it.

Limits

DMA does not go through the MPU, so a DMA channel programmed with a bad destination still writes memory. Region count is also finite, eight on Cortex-M4, so I cannot grant one region per peripheral on a large part. I would group peripherals by bus and grant the group, accepting that a wild write inside the group will not fault. The MPU also has to be programmed before the driver runs, and a HardFault handler that swallows MemManage will hide the fault entirely.

Compared with a software bounds check on every pointer, the MPU costs nothing per access and catches the write at the bus interface. The check costs cycles and misses writes through a cast or a corrupted struct member. The MPU only catches writes outside the granted window, so narrow regions plus normal pointer discipline is the combination that actually works.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-41A deadline check using signed tick arithmetic works at -O0 but the timeout never fires at -O2. How could the optimizer cause that, and what test tells you it is undefined behavior rather than a logic error?

The 90-second answer

That pattern points to signed overflow. In C, signed overflow is undefined behaviour, so at -O2 the compiler is allowed to assume it never happens and simplify code on that basis. At -O0 it usually just emits the add and the hardware wraps, so the bug stays hidden. The test that separates the two cases is to change the assumption and see if the failure follows it. Build with -fwrapv, which defines signed overflow as wrap, or with UBSan enabled. If the timeout starts working again, or UBSan reports the overflow on that line, the optimizer exposed UB. If neither changes anything and the -O2 disassembly faithfully implements your logic, it is a logic bug.

What the optimizer does here

C
int32_t deadline = tick + timeout;
if (tick > deadline) {
    handle_timeout();
}

Take tick = 2147483640 and timeout = 100. The true sum is 2147483740, which exceeds INT32_MAX (2147483647). At -O0 the 32-bit add wraps to a negative value, tick > deadline is true, and the timeout fires by accident. At -O2 GCC reasons that tick + timeout cannot overflow, therefore deadline >= tick must always hold, therefore tick > deadline is always false. It deletes the branch and handle_timeout() is never called. The disassembly at -O2 shows no compare for that condition at all. That missing compare is the giveaway. A logic bug would still have the compare, it would just compute the wrong value.

BuildResult for tick near INT32_MAXWhat it tells you
-O0Wraps, timeout firesHardware behaviour, not proof the code is correct
-O2Branch removed, timeout never firesCompiler used the no-overflow assumption
-O2 -fwrapvWraps again, timeout firesFailure depends on the overflow assumption, so it is UB
-O1 -fsanitize=undefinedReports signed integer overflow at the addPinpoints the UB site

UBSan needs a hosted environment or a small runtime, so on a bare Cortex-M4 target I would run that build in a test harness or under QEMU with the same inputs, and use -Wall -Wextra warnings on the target build as a first pass. A clean UBSan run does not rule out every kind of UB, but for this arithmetic case it is decisive.

The fix

Do the arithmetic in unsigned type, where wrap is defined, and compare using a signed difference:

C
uint32_t deadline = (uint32_t)tick + (uint32_t)timeout;
if ((int32_t)((uint32_t)tick - deadline) > 0) {
    handle_timeout();
}

Now the wrap is intentional and defined, the compiler cannot delete the check, and the comparison stays correct across the INT32_MAX boundary as long as timeout is less than half the range of the tick counter. Rebuild at -O2 and confirm the compare is present in the disassembly and the timeout fires for the values above. If it still fails after that, with UBSan clean and -fwrapv making no difference, then debug it as a logic error in the timeout handling itself.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-42What does strict aliasing forbid in type punning, and why does reading another union member avoid that violation in C?

The 90-second answer

Strict aliasing in C says an object can only be accessed through a pointer to a compatible type, or through a character type. A float and a uint32_t are not compatible, so reading the storage of one through a pointer to the other is undefined behaviour. The compiler relies on that rule to reorder and cache accesses, so it may assume a write through a float* cannot change what a later read through a uint32_t* sees.

A union is the exception in C. All members share the same storage, and GCC and Clang define reading a member other than the one last written. That makes the union the intended way to reinterpret the bits in C, with memcpy as the portable alternative.

The cast that breaks

C
#include <stdint.h>

uint32_t bits_bad(float f)
{
    return *(uint32_t *)&f; /* violates strict aliasing */
}

This often appears to work at -O0. At -O2 the compiler can keep f in a register and reuse a stale integer value, because under the rule the two accesses cannot alias. In firmware that shows up as a conversion that passes in a debug build and fails in the release build, with no change to the source.

The union version

C
#include <stdint.h>
#include <string.h>

union FloatBits {
    float f;
    uint32_t u;
};

uint32_t bits_union(float f)
{
    union FloatBits v = { .f = f };
    return v.u;
}

uint32_t bits_memcpy(float f)
{
    uint32_t u;
    memcpy(&u, &f, sizeof u);
    return u;
}

Both versions describe the same storage, so the compiler must keep the value coherent. At -O2 both compile to a register move, with no extra load or store. The union reads more clearly when you are extracting, say, the exponent from an IEEE-754 sensor value. memcpy has no implementation-defined step, so it is the safer choice in shared code.

MethodStatus in CCost at -O2
Pointer cast *(uint32_t *)&fUndefined behaviourZero until the compiler reorders it
Union member readDefined by GCC and ClangZero, a register rename
memcpyDefinedZero, inlined to a move
char * byte accessAllowed, character types may alias any objectZero, but gives bytes only

One boundary to keep in mind: the union trick is a C rule. In standard C++ it is undefined behaviour, even though GCC and Clang accept it, so C++ code should use memcpy or std::bit_cast from C++20. A union also does not fix layout. It reinterprets bits in place, but padding and endianness still decide where those bits land on the wire.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-43Your Cortex-M0 receives a packed 12-byte sensor frame over UART and faults when you cast it to a struct of uint32_t fields. How do you parse it safely without unaligned access support?

The 90-second answer

Assume a Cortex-M0 or M0+, which faults on an unaligned load or store, and a 12-byte frame in a UART buffer. Casting that buffer to a struct of uint32_t fields is undefined behaviour in C, because the compiler may assume the pointer is 4-byte aligned and emit one aligned load. On the M0 that load faults if the buffer starts at an odd address, or if a header byte shifts the fields.

Copy each field out with memcpy into a normal aligned struct. The destination is aligned, the source only needs byte alignment, and the compiler lowers the copy to byte loads on a strict-alignment core and to a single load where unaligned access is supported.

C
// C11, checked with GCC for Cortex-M0
#include <stdint.h>
#include <string.h>

struct frame { uint32_t ts; uint16_t value; uint16_t flags; uint32_t crc; };

static inline uint32_t u32le(const uint8_t *p) {
    uint32_t v; memcpy(&v, p, 4); return v;
}
static inline uint16_t u16le(const uint8_t *p) {
    uint16_t v; memcpy(&v, p, 2); return v;
}

int parse(const uint8_t *buf, struct frame *out) {
    if (!buf || !out) return -1;
    out->ts = u32le(buf + 0);
    out->value = u16le(buf + 4);
    out->flags = u16le(buf + 6);
    out->crc = u32le(buf + 8);
    return 0;
}

If the wire format is little-endian and the target is not, memcpy gives the wrong value. Assemble the field with shifts instead, p[0] | (p[1] << 8) | (p[2] << 16) | ((uint32_t)p[3] << 24), so the byte order is explicit.

Why it faults

AccessAddressCortex-M0
uint32_t at 0x20000100alignedsucceeds
uint32_t at 0x20000101oddHardFault, UNALIGNEDERR in CFSR
uint16_t at 0x200001022-byte alignedsucceeds
uint16_t at 0x20000101oddHardFault

A Cortex-M4 tolerates unaligned access to normal RAM, which is why this bug often passes on a development board and fails on the M0 product. Do not rely on that difference. On M3 and M4, unaligned access to Device memory such as peripheral registers is not guaranteed to work either, so the same cast is unsafe there too.

Choices and traps

memcpy per field is the default. It costs four byte loads for a uint32_t on the M0, which is acceptable for a 12-byte frame arriving over UART. Byte assembly costs about the same and documents endianness. Copying the whole frame to an aligned scratch buffer does not help if you then cast it to a packed struct, because the members are still at odd offsets inside that struct.

Avoid __attribute__((packed)) structs with members accessed directly. GCC emits byte loads for packed members on ARM, but taking the address of a member and passing it as uint32_t*, or letting optimisation assume alignment, brings the fault back.

Two checks catch most cases in review. First, the parsed struct must be a normal aligned type, not a packed one, and the buffer length must be checked before reading buf + 8, or a short frame reads past the end. Second, align the DMA buffer itself, for example __attribute__((aligned(4))) static uint8_t rx[64];, and confirm the DMA engine's own alignment requirement in its reference manual, since some parts require more than the CPU does. In the HardFault handler, compare the stacked PC with the cast line and check the faulting address. If the PC matches and the address is odd, the trace above is the diagnosis.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-44You are parsing a big-endian protocol on a little-endian Cortex-M4. How do you convert 16-, 32- and 64-bit fields safely, and why not just cast the receive buffer to a struct?

The 90-second answer

Parse the wire bytes explicitly, field by field, and build the host value with shifts. On a little-endian Cortex-M4 the first byte on the wire is the most significant byte for a big-endian protocol, so 0x12 0x34 0x56 0x78 means 0x12345678, while the same bytes in memory as a uint32_t would read as 0x78563412. A cast does not fix that, it just reinterprets the bytes in host order.

C
#include <stdint.h>
#include <string.h>

static inline uint16_t be16(const uint8_t *p)
{
    return (uint16_t)(((uint16_t)p[0] << 8) | p[1]);
}

static inline uint32_t be32(const uint8_t *p)
{
    return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) |
           ((uint32_t)p[2] << 8)  |  (uint32_t)p[3];
}

static inline uint64_t be64(const uint8_t *p)
{
    uint64_t v = 0;
    for (int i = 0; i < 8; i++)
        v = (v << 8) | p[i];
    return v;
}

This is portable, works on an unaligned DMA buffer, and the compiler turns the 32-bit version into a single REV instruction on Cortex-M3/M4. The alternative, memcpy plus __builtin_bswap32(), is equally valid and sometimes clearer when the field is already in a register:

C
uint32_t raw;
memcpy(&raw, p, sizeof(raw));   /* avoids unaligned access and aliasing */
uint32_t value = __builtin_bswap32(raw);

Worked trace

Receive buffer holds a big-endian sequence number and timestamp:

OffsetByteContribution to be32()Running value
00x120x12 << 240x12000000
10x340x34 << 160x12340000
20x560x56 << 80x12345600
30x780x780x12345678

Reading the same four bytes with *(uint32_t *)p on the little-endian core gives 0x78563412. That is the classic symptom in the field: small fields look plausible, counters jump by huge amounts, and a length of 0x0010 becomes 0x1000.

Why not a packed struct cast

ApproachWhat goes wrong
__attribute__((packed)) struct castFields are still laid out in host byte order, so every multi-byte field is byte-swapped relative to the wire. Packed also forces the compiler to generate byte-wise accesses, and the cast itself risks unaligned access faults on Cortex-M0 and strict-aliasing violations.
Shift-and-OR from uint8_t *No alignment requirement, no aliasing issue, explicit about wire order. Cost is one REV or a few shifts per field.
memcpy + __builtin_bswap*Same safety as shifts, handy for 64-bit values and for fields already copied into a local. Depends on a compiler intrinsic, which GCC and Clang both provide for ARM.

htons() and ntohs() from <arpa/inet.h> do the same job on a hosted system, since network order is defined as big-endian. On bare metal that header is usually absent, and writing the shifts keeps the protocol definition visible in the parser instead of hiding it behind a socket API.

Where this bites in practice

Signed fields need care. Sign-extend after conversion, not before: a big-endian int16_t of 0xFFFE is -2, and shifting it as a signed type first gives implementation-defined results. For 24-bit fields, common in sensor protocols, read three bytes and shift, then sign-extend from bit 23 if the value is signed. Bitfields in a struct are the worst trap here, because their allocation order and byte order are implementation-defined, so a bitfield that matches the spec on a big-endian test host can scramble on the little-endian target. Keep bitfields for host-side status registers, never for wire parsing.

Length and offset fields deserve a range check before you trust them. A corrupted length that has been byte-swapped often lands far outside the buffer, so validate length <= remaining before copying or looping. That check also catches the case where the sender and receiver disagree on endianness for only some fields, which happens when a header was written by a different stack.

If you need to confirm the host order at runtime, a union test settles it in two lines: store 0x01020304 in a uint32_t, inspect b[0], and 0x04 means little-endian. In practice you know Cortex-M is little-endian by default, and the explicit shifts make the code correct either way, which is the point of writing it this way.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-45How would you detect a stack overflow on a Cortex-M RTOS task using a canary, a watermark, and an MPU guard region, and when would you use each?

The 90-second answer

Use all three, because they catch different failures. A canary is a magic word placed at the top of the stack and checked on every context switch. It tells you the stack already overflowed, after the fact, at O(1) cost. A watermark fills the whole stack with a known pattern at creation and you scan for the lowest untouched word. It tells you how close you came, before you overflow, but only when you scan. An MPU guard region makes the memory just below the stack inaccessible. The first write past the end raises a MemManage fault at the exact instruction, which is the only one of the three that prevents corruption instead of reporting it.

On a Cortex-M4 running FreeRTOS with a 1 KB task stack, I would enable the canary in production, measure the watermark in test, and add an MPU guard on the safety task if I can spare one of its 8 MPU regions.

Canary: cheap, late

FreeRTOS configCHECK_FOR_STACK_OVERFLOW 2 writes a known value at the stack limit and checks it in vTaskSwitchContext. The check is one load and compare per switch, roughly a few cycles, and it fires before the next task runs. The weakness is timing. Between switches the task can overflow, corrupt the adjacent heap or another stack, and return, leaving the canary intact if the overwriting data happens to restore it or never reached it. It also cannot tell you how far past the end you went.

C
/* Checked on context switch, configCHECK_FOR_STACK_OVERFLOW 2 */
#define STACK_CANARY 0xC0FFEE11UL

void vApplicationStackOverflowHook(TaskHandle_t xTask, char *pcTaskName)
{
    (void)xTask;
    /* Log pcTaskName and the current SP, then reset. Do not return. */
    taskDISABLE_INTERRUPTS();
    for (;;) { }
}

Watermark: sizing, not protection

At task creation the stack is filled with 0xA5. uxTaskGetStackHighWaterMark() scans from the top and returns the number of words never written. If a 1 KB stack shows 64 bytes free after a stress run, your worst case margin is 64 bytes, not the 1 KB you allocated. Run this in the idle task or a test harness, never on every switch, because a full scan is O(stack size). It is also blind between scans. A task that spikes to 1.1 KB for 2 ms and returns will look safe if you scan afterwards. Use it to size stacks and to catch growth trends in soak tests, not as a runtime guard.

MPU guard: precise, costs a region

Place a no-access region immediately below the stack base. Cortex-M MPU regions must be at least 32 bytes, size aligned, and the size must be a power of two. For a 1 KB stack at 0x20001C00, a 32 byte guard at 0x20001BE0 with AP = none catches the first write below 0x20001C00. The core raises a precise MemManage fault, MMFSR shows the faulting address, and the stacked PC points at the store that crossed the line. No corruption has happened yet.

C
/* CMSIS, Cortex-M4. Guard sits below the stack base. */
ARM_MPU_RASR(0, 0, 0, 0, 1, 0, 0, ARM_MPU_AP_NONE, ARM_MPU_XN);
/* Region 0: 32 bytes, no access, execute never */

The cost is real. The M4 has 8 regions. The kernel, the guard, and any peripheral protection you already use (for example, blocking writes to a control register) compete for them. A guard also only helps if the stack actually grows into it. A wild pointer write from elsewhere in RAM will not touch the guard and will not fault. And if your linker placed the heap directly below the stack, the guard must sit between them, which may force you to move the heap.

MethodWhen it firesRuntime costWhat it cannot do
CanaryNext context switch after overflow1 load/compare per switchPrevent corruption, measure margin
WatermarkWhen you scan (idle task, test)O(stack) per scanCatch a transient spike between scans
MPU guardFirst access below stack baseZero until fault, 1 region alwaysCatch wild writes that skip the guard

How I combine them

In development I log the watermark after each test scenario and resize any stack under 20% free. In production I keep the canary on for every task, because it costs almost nothing and catches the common case of a deep call chain in a low priority task. For the one or two tasks where corruption would be unsafe, such as the control loop, I spend an MPU region on a guard and route the MemManage handler to log the faulting address from MMFAR and reset. That split keeps the region budget intact while giving precise detection where the consequence of a silent overwrite is worst.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-46Why does heap fragmentation get worse over long uptime, and why do you prefer static allocation in firmware?

The 90-second answer

With a general-purpose heap, repeated malloc and free of different sizes leaves holes that no single allocation can use. Total free memory can look healthy while a request for a large contiguous block fails, and that failure becomes more likely the longer the device runs because allocation patterns drift away from the clean state at boot. In firmware I avoid that failure mode by allocating at build or boot time: fixed buffers placed by the linker, or a fixed-size pool with a free list. The memory cost is known before the device ships, and the same request cannot start failing in month six.

How fragmentation develops

A heap allocator splits a large region into blocks with headers. Freeing a block creates a hole. Adjacent holes can be coalesced, but holes separated by a live block cannot. Over time, short-lived allocations of varying sizes (for example, a 96-byte packet, then a 1,024-byte DMA buffer, then a 64-byte string) punch holes in different places. A later 2,048-byte request needs one contiguous 2,048-byte hole, not 2,048 bytes spread across five holes.

Internal fragmentation is different: a block handed out is larger than requested because of alignment or a minimum block size. External fragmentation is the contiguous-block problem above, and it is the one that bites at runtime.

Worked trace, hypothetical 16 KB heap laid out in order, block sizes rounded to allocator granularity:

| Step | Action | Total free | Largest contiguous hole | Result | | --- | ---: | ---: | --- | | 1 | Alloc A 4 KB, B 2 KB, C 4 KB, D 2 KB | 4 KB | 4 KB | all succeed, layout A B C D tail | | 2 | Free A and C | 12 KB | 4 KB | holes at A, C and the tail | | 3 | Alloc E 3 KB | 9 KB | 4 KB | E takes the first 3 KB of A, leaves a 1 KB sliver | | 4 | Alloc F 5 KB | 9 KB | 4 KB | fails, despite 9 KB free in total | | 5 | Free B 2 KB | 11 KB | 4 KB | B coalesces only with the 1 KB sliver next to it, giving a 3 KB hole |

At step 4 the device has more than enough bytes in aggregate. It does not have them in one place. At step 5, freeing B does not create a large hole because E still sits between the sliver and C, and D still sits after C. Compaction would fix it, but moving live blocks on a microcontroller costs time, breaks pointers other code may hold, and is not offered by typical embedded malloc implementations.

Why static allocation wins in firmware

C
#define UART_RX_SIZE 256u

static uint8_t uart_rx[UART_RX_SIZE] __attribute__((aligned(4)));
static uint8_t uart_rx_head;
static uint8_t uart_rx_tail;

The linker reserves uart_rx in .bss. If it does not fit, the build fails on the bench, not in the field. There is no allocator header per block, no NULL return to check on every call, and no dependence on the order in which tasks happened to run at boot. Worst-case RAM use is a sum you can audit in the map file.

A fixed pool keeps some flexibility without the fragmentation problem:

C
#define POOL_BLOCKS 8u
#define POOL_BLOCK_SIZE 128u

static uint8_t pool[POOL_BLOCKS][POOL_BLOCK_SIZE];
static uint8_t pool_free[POOL_BLOCKS] = {1, 1, 1, 1, 1, 1, 1, 1};

Every block is the same size, so any free block satisfies any request up to 128 bytes. Allocation is a scan of eight flags. The trade-off is internal waste: a 20-byte request consumes a 128-byte block. That waste is bounded and visible, which is the point.

FreeRTOS makes the same choice explicit. heap_1 allocates and never frees, which suits a system where every allocation is made at startup. heap_4 coalesces adjacent free blocks and is the usual choice when freeing is unavoidable, but it still cannot coalesce non-adjacent holes.

When I would still use the heap

A heap is reasonable for a one-time allocation during initialisation, followed by no further allocation, or on a larger SoC running Linux where the process can be restarted and memory is plentiful. On a bare-metal or RTOS target with a fixed RAM budget, a watchdog, and a requirement to run for years, I size the static buffers from measured worst cases, add a guard or canary where corruption is a concern, and treat any runtime allocation request as a design error to be removed. The failure I am avoiding is not a crash on day one. It is a malloc that returns NULL at 03:00 in year three, in a code path that was tested for a week and passed.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-47You have 2 KB of RAM for a lookup table holding up to 96 sensor calibrations keyed by 32-bit IDs, with lookups in a 1 kHz control loop. How do you choose the hash table design and prove it fits and meets timing?

The 90-second answer

I would not start with the hash function. I would start with whether the key set is known at build time, because that decides the design. If the 96 sensor IDs are fixed for a product variant, a sorted array or a generated perfect hash beats a general hash table on RAM and worst-case time. If IDs arrive at runtime, are added or removed, and the table must live in 2 KB, I would use open addressing with linear probing, a power-of-two size, separate arrays for key and value, and a hard cap on load factor. No malloc, no pointers per entry, no unbounded probe chain in the control loop.

Assume a Cortex-M4 at 168 MHz, a 1 kHz loop, keys are uint32_t sensor IDs, values are a uint16_t calibration index, and ID 0 is reserved as empty. That assumption matters: with a reserved sentinel I need no state byte per slot.

Sizing with real numbers

A 256-slot table gives load factor alpha = 96 / 256 = 0.375 at full capacity. Storage is 256 x 4 bytes for IDs plus 256 x 2 bytes for values = 1536 bytes, leaving about 512 bytes of the 2 KB budget for the rest of the subsystem. A 128-slot table would use 768 bytes but alpha = 0.75, and for linear probing the expected probes for an unsuccessful search rise to roughly 8.5. At alpha = 0.375 the expected figures are about 1.3 probes for a hit and 1.8 for a miss. That is the trade I want in a 1 kHz loop: spend RAM I have to buy a short, predictable probe chain.

Masking with & 255 also avoids a modulo division on every lookup. On a Cortex-M4 a 32-bit divide is tens of cycles and adds jitter I do not need.

The design I would ship for a dynamic set

C
/* Checked against C11, Cortex-M4, no dynamic allocation. */
#define HT_SIZE   256u
#define HT_MASK   (HT_SIZE - 1u)
#define HT_EMPTY  0u

static uint32_t ht_id[HT_SIZE];
static uint16_t ht_cal[HT_SIZE];

static inline uint32_t ht_hash(uint32_t id)
{
    /* Knuth multiplicative hash: use high bits, not low bits. */
    return (id * 2654435761u) >> 24; /* 0..255 for HT_SIZE 256 */
}

bool ht_lookup(uint32_t id, uint16_t *cal_out)
{
    if (id == HT_EMPTY) return false;
    uint32_t i = ht_hash(id);
    for (uint32_t n = 0; n < HT_SIZE; n++) {
        uint32_t key = ht_id[i];
        if (key == HT_EMPTY) return false;
        if (key == id) { *cal_out = ht_cal[i]; return true; }
        i = (i + 1u) & HT_MASK;
    }
    return false; /* table full: caller treats this as a fault, not a miss */
}

Using the high bits of the multiplicative product matters here. Sensor IDs often differ only in low bits, for example 0x1001, 0x1002, 0x1003. A hash that took id & 255 would map a whole family of sequential IDs to consecutive slots and cluster badly under linear probing. The multiplicative hash spreads sequential IDs across the table.

Worked trace, hypothetical IDs, table initially empty:

InsertHash slotProbesFinal slot
0x100141141
0x100241242
0x100397197
0x1001 again41141, duplicate rejected

The second insert shows the cost of a collision: one extra probe, still bounded. The bound is the point. The loop cannot run past 256 iterations, and at alpha = 0.375 a chain that long means the table is corrupt or full, so I surface it instead of spinning in the control loop.

When I would choose something else

DesignRAM for 96 entriesWorst-case lookupDeletionWhen I pick it
Sorted array + binary searchabout 576 bytes7 comparisons, deterministicO(n) shiftIDs fixed, sorted at build or boot, smallest RAM
Minimal perfect hash, generated offlineabout 576 bytes plus parameters1 proberebuild requiredKey set frozen per variant, tightest timing
Open addressing, linear probing1536 bytes at 256 slotsbounded by table size, short at low alphatombstones or rehashRuntime insert and lookup, moderate RAM
Separate chaining with nodes96 x (overhead + node) plus poolchain length unbounded in principleeasyI would avoid it here: pointer chasing, fragmentation risk, pool sizing still needed

For a frozen set I would generate a perfect hash on the host, ship the parameters as const data in flash, and keep only the value array in RAM. That removes the empty sentinel and the probe loop entirely. The catch is operational: a new sensor ID means regenerating and requalifying the table, so it only works when the hardware population is truly fixed.

Failure modes I would test for

Deletion is the sharp edge. Linear probing cannot just clear a slot, or lookups for later entries in the cluster stop early at the empty slot. The options are tombstones, which make unsuccessful searches degrade as tombstones accumulate, or backward-shift deletion, which is more code to verify. My rule: if sensors can be removed at runtime, count tombstones and rebuild the table when tombstones exceed, say, 32, and do the rebuild outside the control loop or in a critical section with the loop told to use the last good calibration. If removal never happens, I delete the deletion code path and say so in the design note.

The second failure mode is silent overload. If firmware accepts a 97th sensor into a table sized for 96 at alpha 0.375, nothing breaks immediately, which is exactly the danger. I would cap inserts at a compile-time HT_MAX_ENTRIES of 96, return an error on the 97th, and add a boot-time check that the measured maximum probe length stays under a threshold such as 8. I would log that maximum in a debug build. A hash table that only fails under load in the field is a table I sized by hope.

Finally, concurrency. If an ISR or another task inserts while the control loop looks up, a torn read can return a half-written key. On a 32-bit aligned load that is unlikely on Cortex-M4, but the probe sequence itself can still race. I would either build the table once at boot before the scheduler starts, or guard inserts with a short critical section and keep lookups lock-free only if inserts never move an existing entry. That constraint, more than the hash function, is what makes the design safe to ship.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-48How would you implement a circular buffer for a UART receive stream where an ISR produces bytes and a task consumes them, with reliable full and empty detection?

The 90-second answer

Use a single-producer, single-consumer ring buffer. The UART ISR is the only writer of head, the consuming task is the only writer of tail, and neither side needs a lock. Keep head and tail as monotonically increasing 32-bit counters, not as pointers that wrap at the end of the array. Then the number of bytes in the buffer is always head - tail, so full and empty are unambiguous even after the indices wrap past the array size many times.

C
/* Checked against C11 on Cortex-M4. UART_RX_SIZE must be a power of two. */
#define UART_RX_SIZE 256U
#define UART_RX_MASK (UART_RX_SIZE - 1U)

typedef struct {
    uint8_t buf[UART_RX_SIZE];
    volatile uint32_t head;    /* written by ISR only */
    volatile uint32_t tail;    /* written by task only */
    volatile uint32_t dropped; /* written by ISR only */
} uart_rx_ring_t;

static uart_rx_ring_t rx;

/* Called from the UART receive ISR. */
static bool rx_push_isr(uint8_t byte)
{
    uint32_t head = rx.head;

    if ((head - rx.tail) >= UART_RX_SIZE) {
        rx.dropped++;
        return false;
    }
    rx.buf[head & UART_RX_MASK] = byte;
    rx.head = head + 1U; /* publish the byte only after it is stored */
    return true;
}

/* Called from the consuming task. */
static bool rx_pop_task(uint8_t *byte)
{
    uint32_t tail = rx.tail;

    if (tail == rx.head) {
        return false;
    }
    *byte = rx.buf[tail & UART_RX_MASK];
    rx.tail = tail + 1U;
    return true;
}

volatile on head and tail stops the compiler caching them in registers across calls, which matters because the other side changes them asynchronously. On a single-core Cortex-M, aligned 32-bit loads and stores are not torn, so the reader either sees the old index or the new one. That guarantee disappears on a multicore part or when DMA writes the buffer, where you would need the platform atomic or barrier primitives instead of relying on volatile.

Why monotonic indices instead of head-equals-tail

With plain array indices, head == tail means both empty and completely full, so the usual fix is to waste one slot and declare full when (head + 1) & mask == tail. That works, but it throws away a byte and the test is easy to get wrong. With monotonic counters, unsigned subtraction gives the occupancy directly, and the 32-bit wrap is harmless: after 2^32 bytes, head - tail still computes correctly as long as occupancy never exceeds 2^31, which a 256-byte buffer cannot reach.

Worked trace for a size-8 buffer, starting empty:

StepActionheadtailOccupancy (head - tail)Result
1ISR pushes A, B, C3033 bytes stored
2Task pops A, B321C remains
3ISR pushes 7 more bytes1028buffer full, next push drops
4Task pops 8 bytes10100empty, head == tail
5ISR pushes Z11101stored at buf[11 & 7] = buf[3]

Note step 5: the write position cycles through the array via the mask, while the counters keep climbing. That separation is what makes the full and empty tests trivial.

Sizing and overflow policy

At 115200 baud with 8N1 framing, each byte costs 10 bit times, so the line delivers about 11520 bytes per second. A 256-byte buffer therefore absorbs roughly 22 ms of consumer stall before it fills. If your task runs every 10 ms and can be delayed by a lower-priority section, that margin is thin, and the dropped counter is how you find out in the field instead of guessing. On overflow I drop the incoming byte and count it, rather than overwriting the oldest data, because a UART stream usually has framing the receiver can resynchronise on, whereas silently overwriting the middle of a packet corrupts data you have already committed to parsing. If the protocol has no resync, the alternative is to stop the sender with RTS or XOFF before the buffer fills, which costs flow-control pins or latency but loses nothing.

The failure mode to watch is not the buffer logic, it is the consumer falling behind permanently: occupancy pinned at full, dropped climbing, and the ISR still returning quickly. That points at task priority, a blocking call in the consumer, or a baud rate the task was never sized for, and no amount of index cleverness fixes it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-49You maintain a device list on a microcontroller where new devices are usually added at the head and the list is iterated in order. When would you choose a linked list over an array, and what does each choice cost you?

The 90-second answer

For a device list where the common mutation is "add a new device at the head" and you rarely need random access by index, a singly linked list wins on insertion cost. Head insertion is one pointer write, O(1), regardless of list length. An array pays O(n) on every head insertion because every existing element has to move. The price is everything else: no indexing, pointer chasing on traversal, per-node overhead, and allocation failure modes that an array with a fixed capacity does not have.

On a microcontroller that trade is usually decided by three facts: how many devices can exist at once, whether allocation can fail or fragment, and whether you ever need element i directly.

Head insertion, concretely

C
/* Checked against C11, 32-bit Cortex-M: pointers are 4 bytes. */
typedef struct device {
    uint8_t  id;
    uint8_t  type;
    uint16_t state;
    struct device *next;   /* 4 bytes, struct is 8 bytes total */
} device_t;

static device_t *head;     /* NULL when empty */

bool device_add_head(device_t *d)
{
    if (d == NULL) return false;
    d->next = head;
    head = d;
    return true;
}

The array equivalent has to shift the whole list:

C
#define MAX_DEVICES 64
static device_t devices[MAX_DEVICES];
static uint8_t  device_count;

bool device_add_head_array(const device_t *d)
{
    if (device_count >= MAX_DEVICES) return false;
    memmove(&devices[1], &devices[0],
            (size_t)device_count * sizeof(device_t));
    devices[0] = *d;
    device_count++;
    return true;
}

Worked trace with 64 devices of 8 bytes each, inserting at the head:

StructureBytes moved on insertPointer writesWorst case as list grows
Array, 64 entries63 x 8 = 504 bytes0O(n), grows with count
Linked list02 (d->next, head)O(1)

504 bytes is about 126 word copies on a Cortex-M4. That is fast in isolation, but if insertion happens in a control loop or an ISR-adjacent context, the cost is proportional to a list you do not control at compile time. The linked list cost does not grow.

Comparison on the operations you actually do

OperationArray (fixed capacity)Singly linked list
Insert at headO(n) memmoveO(1)
Insert at tailO(1) if count trackedO(n) unless tail pointer kept
Access by indexO(1)O(n) walk
Iterate allContiguous, one cache line per ~8 entriesPointer chase, one node per cache line at best
Delete by pointerO(n) to close gapO(1) if predecessor known
Memory overheadMAX_DEVICES * sizeof always reserved4-byte next per node, only allocated nodes used
Failure modeReturns false when full, predictableAllocation failure, fragmentation, dangling pointer

Iteration is where the array quietly wins. Walking 64 linked nodes touches 64 scattered addresses. On a cache-enabled part that is 64 cache misses in the worst case, against a sequential scan of 512 contiguous bytes. If the list is walked every control cycle, that difference shows up as jitter.

Embedded constraints that decide it

Fixed maximum, known at design time: use the array. You reserve 64 * 8 = 512 bytes in .bss, the linker proves it fits, insertion failure is a clean false, and there is no heap involved. This is the default for a device table on a 16 KB RAM part.

Variable count, nodes already exist elsewhere: use the list. If each device already has a control block allocated for its driver state, linking those blocks costs only the next pointer and avoids copying the whole struct on every insert. That is the classic case: the list is a view over objects you already own.

Never call malloc for nodes from an ISR or from a task where allocation latency matters. On FreeRTOS, heap_4 still fragments under interleaved alloc and free, and a failed allocation in a hot path is a silent drop. If you want a list without heap risk, allocate a static pool and link from it:

C
static device_t pool[MAX_DEVICES];
static device_t *free_list;  /* stack of unused pool entries */

You keep the O(1) head insertion and you keep the failure mode of the array: pool empty means NULL, no fragmentation, and the bound is visible in the map file.

Two failure modes to name in the interview. First, a corrupted next pointer walks the list into unmapped memory or loops forever, and there is no bounds check to catch it. A count field alongside head, checked during debug builds, catches loops. Second, deleting a node while another task or ISR is traversing it leaves a dangling traversal. That needs the same critical section discipline as any shared structure: short taskENTER_CRITICAL around the pointer updates, never around a full traversal.

Rule of thumb: head insertions dominate, index access is rare, nodes already exist or come from a static pool, choose the list. Everything else, choose the array and pay the memmove.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-50How does an explicit stack bound the nesting depth when parsing nested protocol frames?

The 90-second answer

An explicit stack stores one parser context per open frame in a fixed array. When a start marker arrives you push a new context. When an end marker arrives you check the context on top, pop it, and pass the finished frame to the level below. Because the array has a compile time size, nesting depth has a compile time limit. If a peer sends more start markers than the array holds, you reject the frame instead of overflowing the call stack.

That bound is the whole reason to prefer it over recursion on a microcontroller. A recursive parser gets its depth limit from whatever stack space happens to remain, and its frame size is chosen by the compiler. An explicit stack makes both numbers visible in the RAM budget.

C
#define MAX_DEPTH 8

typedef struct {
    uint8_t  type;
    uint16_t remaining;  /* payload bytes still expected */
    uint16_t crc;        /* running CRC-16 over payload */
} frame_ctx_t;

typedef struct {
    frame_ctx_t ctx[MAX_DEPTH];
    uint8_t     sp;      /* frames currently open */
} parser_t;

static int on_start(parser_t *p, uint8_t type, uint16_t len)
{
    if (p->sp >= MAX_DEPTH) {
        return -1;       /* too deep: reject, do not push */
    }
    frame_ctx_t *c = &p->ctx[p->sp++];
    c->type = type;
    c->remaining = len;
    c->crc = 0xFFFF;
    return 0;
}

static int on_end(parser_t *p, uint8_t type, uint16_t crc)
{
    if (p->sp == 0) return -1;
    frame_ctx_t *c = &p->ctx[p->sp - 1];
    if (c->type != type || c->remaining != 0 || c->crc != crc) {
        return -1;
    }
    p->sp--;
    deliver_frame(c->type);
    return 0;
}

Each context here is 6 bytes, so 8 levels cost 48 bytes of static RAM. You can read that figure in the linker map. A recursive version gives you no equivalent line to check.

Worked trace

Outer frame type 0x10 contains one inner frame type 0x20 with payload AA BB:

StepInputActionsp after
1start 0x10push outer context1
2start 0x20push inner context2
3data AA, BBupdate inner CRC, remaining reaches 02
4end 0x20, CRC matchespop inner, deliver to outer level1
5end 0x10, CRC matchespop outer, deliver frame0

Failure mode

The failure this design exists to catch is depth overflow. A faulty or hostile peer can send start markers with no matching end markers. With recursion that stream consumes call stack until the core faults or corrupts adjacent RAM. With the fixed array, the ninth start marker hits the sp >= MAX_DEPTH check, returns an error, and the parser resets sp to 0 so the next valid frame can be found. Count those rejections in a diagnostic counter, because a link that rejects frames every few seconds is telling you something about the sender or the wiring.

Start Data End Yes Next token Token type Push context if depth allows Update top context and CRC Check top context, then pop Deliver frame to parent Error? Reset sp to 0

The parser can also stop between chunks, because all of its state lives in parser_t rather than in call frames. That matters when bytes arrive from a UART or DMA buffer in pieces that do not align with frame boundaries.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-51Your 10 Hz temperature sensor can freeze at one value or drift slowly while the real temperature moves, how would you use sliding windows to detect both on a Cortex-M0 without floating point?

The 90-second answer

Keep two windows over the same ring buffer. A short window of 8 samples and a long window of 32 samples at 10 Hz. Stuck means the long window has almost no spread while the sensor should show noise. Drift means the mean of the last 8 samples has moved away from the mean of the previous 24 by more than noise allows, and stays there. Neither test alone is enough. A sensor in a steady state can sit flat for minutes, and a real temperature ramp looks like drift for a few seconds. I gate both tests on expected excitation and require persistence before I raise a fault.

Assume a temperature sensor reporting int16_t in 0.01 C units, sampled at 10 Hz on a Cortex-M0 with no FPU. The datasheet gives noise sigma of 4 counts and resolution of 6 counts. Those two numbers set every threshold. I use integer arithmetic only, and a 32 entry ring buffer costs 64 bytes.

Stuck detection

For each new sample I update the ring buffer and recompute min, max and sum over the long window. At 10 Hz and N=32 that is 32 iterations per sample, trivial. Stuck is a candidate when max - min <= 1 count. That is below one LSB of real resolution, so a live sensor cannot produce it except by chance. With sigma 4 counts, the probability that 32 independent samples all land within a 1 count band is vanishingly small.

The counter increments once per sample, not once per window. I require 20 consecutive candidate samples before faulting. A frozen sensor needs 32 samples to flush the long window, so the earliest fault is about 5.2 s after the freeze, 3.2 s to flush plus 2.0 s of persistence. That delay is the price of a low false alarm rate.

The gate is excitation. If the heater has been off and the setpoint has not changed, a flat reading is plausible. If heater duty has been above 30% for the whole window and the reading has not moved by even 1 LSB, the flatness is evidence. I pass a process_active flag into the detector and only count candidate samples while it is set.

Drift detection

Drift is a mean shift, not a spread change. I compare the mean of the last 8 samples with the mean of the previous 24 samples, both taken from the same 32 sample buffer. The sliding sum makes this O(1) apart from the 8 sample sum. The standard error of the difference is sigma * sqrt(1/8 + 1/24) = 4 * 0.408 = 1.63 counts. A threshold of 10 counts is about 6 sigma, so a single sample crossing it is already suspicious. I require 8 consecutive samples above threshold, 0.8 s of sustained offset, before declaring drift.

A real ramp also produces this pattern, so I inhibit drift detection for 5 s after a setpoint change or heater step, and I check the sign. Drift from a failing sensor usually walks one way regardless of process direction. If the short mean moves toward the setpoint while the process is driving that way, I treat it as process, not fault.

C
/* C11, checked on Cortex-M0, 10 Hz sample, int16_t in 0.01 C */
#define N_LONG 32
#define N_SHORT 8
#define N_PREV 24

typedef struct {
    int16_t buf[N_LONG];
    uint8_t idx;
    int32_t sum_long;
    uint8_t stuck_count;
    uint8_t drift_count;
    bool fault_stuck;
    bool fault_drift;
} detector_t;

void detector_push(detector_t *d, int16_t sample, bool process_active)
{
    d->sum_long += (int32_t)sample - d->buf[d->idx];
    d->buf[d->idx] = sample;
    d->idx = (uint8_t)((d->idx + 1) % N_LONG);

    int16_t mn = d->buf[0], mx = d->buf[0];
    for (int i = 1; i < N_LONG; i++) {
        if (d->buf[i] < mn) mn = d->buf[i];
        if (d->buf[i] > mx) mx = d->buf[i];
    }
    bool flat = (mx - mn) <= 1;
    if (flat && process_active) {
        if (d->stuck_count < 20) d->stuck_count++;
    } else {
        d->stuck_count = 0;
    }
    d->fault_stuck = d->stuck_count >= 20;

    int32_t sum_short = 0;
    for (int i = 0; i < N_SHORT; i++) {
        uint8_t p = (uint8_t)((d->idx + N_LONG - 1 - i) % N_LONG);
        sum_short += d->buf[p];
    }
    int32_t sum_prev = d->sum_long - sum_short;
    int32_t mean_short = sum_short / N_SHORT;
    int32_t mean_prev = sum_prev / N_PREV;
    int32_t diff = mean_short - mean_prev;
    if (diff < 0) diff = -diff;
    if (diff > 10) {
        if (d->drift_count < 8) d->drift_count++;
    } else {
        d->drift_count = 0;
    }
    d->fault_drift = d->drift_count >= 8;
}

Worked trace

Hypothetical run, heater active throughout, values in counts. The sensor freezes at t=0 and later drifts at t=10.

t (s)Long rangeShort-prev diffStuck countDrift countVerdict
0.018200normal
3.21110window just flushed, counting
5.200200stuck fault
10.0221101offset, counting
10.7241308drift fault
12.030400recovered

Failure modes I would name in the interview

Saturation at the rail also gives zero range. If the sensor is pinned at its maximum code, the detector reports stuck, but the cause is overrange, not a frozen ADC. I check for rail codes first and report overrange instead. Quantization is the other trap. A sensor with 1 C resolution on a slow process can legitimately repeat one code for 32 samples. The threshold must be tied to the LSB, not copied from another sensor. Finally, drift detection will fire on a genuine fast ramp if the inhibit window is too short. I size the inhibit from the process time constant, not from convenience, and I log the raw window statistics with the fault so a field return can be replayed offline.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-52You have a sorted sensor log in flash and need to find duplicate timestamps and pairs of readings that sum to a target without extra RAM: how do you use two pointers for each?

The 90-second answer

If the log is sorted by timestamp or by reading, two pointers give you an O(n) scan with O(1) extra RAM. That matters on a Cortex-M where a hash table for 100,000 entries would not fit in SRAM and would cost flash and lookup time in a control loop. One pointer walks the array. The second pointer either trails it by one for duplicates, or starts at the opposite end for a pair sum.

Assume the log is an array of structs sorted ascending by the key you search on, stored in flash or RAM and readable by index. State that assumption first. If arrival order broke the sort, neither algorithm is valid and you need to sort or use a hash set.

Duplicates: adjacent pointers

Duplicates in a sorted array must be adjacent. Keep i at the current element and compare a[i] with a[i+1]. Advance i by one each step. When the keys match, you have a duplicate run. Skip the whole run before reporting, or you will report the same timestamp three times.

C
#include <stdint.h>
#include <stddef.h>

typedef struct { uint32_t ts_ms; int16_t value; } sample_t;

/* Calls cb once per duplicate run. Returns number of runs. */
size_t find_duplicate_runs(const sample_t *a, size_t n,
                          void (*cb)(uint32_t ts_ms, size_t count))
{
    size_t runs = 0;
    size_t i = 0;
    while (i + 1 < n) {
        if (a[i].ts_ms == a[i + 1].ts_ms) {
            size_t j = i + 1;
            while (j < n && a[j].ts_ms == a[i].ts_ms) j++;
            if (cb) cb(a[i].ts_ms, j - i);
            runs++;
            i = j;
        } else {
            i++;
        }
    }
    return runs;
}

This is O(n) time, O(1) space. A hash set would also be O(n) average time but needs O(n) space for the set, plus handling of collisions and a hash function for 32-bit keys. On a 64 KB RAM part, storing 100,000 timestamps in a hash table is not an option.

Pairs summing to a target: opposite ends

Sort by value instead of timestamp for this task. Put lo at index 0 and hi at index n-1. Compute the sum in a wider type. If the sum is below target, lo is too small, so increment it. If the sum is above target, decrement hi. If it matches, record the pair and move both pointers inward, skipping duplicates of the values just used if you want unique pairs.

C
/* a sorted ascending by value. Returns 1 if a pair was found. */
int find_pair(const int16_t *a, size_t n, int32_t target,
              size_t *out_lo, size_t *out_hi)
{
    if (n < 2) return 0;
    size_t lo = 0, hi = n - 1;
    while (lo < hi) {
        int32_t sum = (int32_t)a[lo] + (int32_t)a[hi];
        if (sum == target) { *out_lo = lo; *out_hi = hi; return 1; }
        if (sum < target) lo++; else hi--;
    }
    return 0;
}

Worked trace for a = [-5, 1, 3, 4, 7, 9], target 10:

Steplohia[lo] + a[hi]Action
10 (-5)5 (9)4sum < 10, lo++
21 (1)5 (9)10match, return (1, 5)

Two steps instead of checking all 15 combinations. In general the pointers meet after at most n-1 moves, so O(n) time and O(1) space. Binary search per element would be O(n log n) and still needs the sorted array.

ApproachTimeExtra RAMNeeds sorted inputNotes
Two pointersO(n)O(1)YesBest fit for flash log, no allocation
Hash setO(n) avgO(n)NoFails on small RAM, worst case degrades
Binary search per itemO(n log n)O(1)YesMore cache or flash accesses per item
Brute force pairsO(n^2)O(1)No100k entries means about 5e9 checks

Failure modes to name

Unsorted input is the main one. A sensor log written by DMA into a circular buffer can wrap, so the array as stored is not sorted across the wrap point. Linearise it or find the rotation point first, otherwise the duplicate scan misses the pair that straddles the wrap and the pair scan moves the wrong pointer. Detect this by checking monotonicity in a debug build or by asserting a[i] <= a[i+1] during a one-time validation pass after a format change.

Integer overflow is the second. Two int16_t values fit in int32_t, but two uint32_t timestamps or readings do not fit in uint32_t when summed. Widen to uint64_t before adding, or compare a[lo] > target - a[hi] with care for signed targets. A sum that wraps looks like a match or a miss depending on the values.

The third is duplicate handling in the pair search. If the log has many repeated values, moving only one pointer after a match can report the same value pair many times and can also miss a valid pair. Skip all copies of a[lo] and a[hi] after a match when unique value pairs are required.

On flash, random access by index is cheap on internal flash but a log streamed over SPI flash costs a page read per jump. The opposite-ends scan jumps between the start and end of the log, so for a large SPI-backed log, buffering a block of, say, 256 samples in RAM and scanning within the block keeps the access pattern sequential. That keeps the O(1) extra RAM claim honest in practice.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-53Walk me through how you would binary search a sorted calibration table in a 1 kHz loop, and how you handle inputs below, above, or between entries?

The 90-second answer

Assume the table is sorted by raw ADC code, stored as const in flash, and never changes at runtime. I search for the first entry whose key is greater than the input, then interpolate between that entry and its predecessor. That gives me a bracketing pair in ceil(log2(n)) comparisons, with no allocation and a bounded worst case I can put in a 1 kHz loop.

The policy for out-of-range inputs has to be decided before coding. For a sensor that saturates, I clamp to the first or last calibrated value. Extrapolation is only defensible if the physics is known to stay linear past the ends, and I would need a test to prove it. Clamping is the safer default because an extrapolated value can drive an actuator far past its tested range.

C
#include <stddef.h>
#include <stdint.h>

typedef struct { uint16_t raw; int32_t milli; } CalPoint;

/* Returns milli-units. Table must be sorted by raw, spans > 0. */
int32_t cal_lookup(const CalPoint *t, size_t n, uint16_t raw)
{
    if (n == 0) return 0;              /* caller must treat as fault */
    if (n == 1 || raw <= t[0].raw) return t[0].milli;
    if (raw >= t[n - 1].raw) return t[n - 1].milli;

    size_t lo = 0, hi = n;             /* invariant: t[lo].raw <= raw < t[hi].raw */
    while (hi - lo > 1) {
        size_t mid = lo + (hi - lo) / 2;   /* no lo+hi overflow */
        if (t[mid].raw <= raw) lo = mid; else hi = mid;
    }
    /* Interpolate between lo and hi == lo+1, in 64-bit to avoid overflow. */
    int64_t dx = (int64_t)t[hi].raw - t[lo].raw;
    int64_t dy = (int64_t)t[hi].milli - t[lo].milli;
    int64_t num = dy * ((int64_t)raw - t[lo].raw);
    return (int32_t)(t[lo].milli + num / dx);
}

Worked trace

Table: [(0,0), (100,1000), (250,2600), (600,6100), (1000,10000)], input raw = 420.

Steplohimidt[mid].rawDecision
1052250250 <= 420, lo = 2
2253600600 > 420, hi = 3
323--hi - lo == 1, stop

Bracket is 250 to 600. Interpolation: 2600 + (6100-2600)*(420-250)/(600-250) = 2600 + 3500*170/350 = 4300. Result 4300 milli-units. Three iterations for five entries, and the count depends only on n, not on where the input falls.

Edge cases that break a naive version

Empty table: the code above returns 0, but that is a placeholder. In production I would return a status code and let the caller hold the last good value or enter a safe state, because 0 is a plausible measurement. Single entry: no bracket exists, so the only honest answer is that entry's value, with the same clamp caveat.

Duplicate keys: if two entries share raw = 250, the span dx for that pair is zero and interpolation divides by zero. The search as written lands on the last duplicate for an exact match, because <= moves lo past duplicates. That is correct for a step-like calibration, but the table generator must still be checked. I add a boot-time or build-time check that keys are strictly increasing and spans are non-zero, and I would rather fail the build than ship a table that faults only for inputs in a narrow band.

Unsorted table: binary search does not degrade gracefully, it returns a wrong bracket silently. This is the most likely field failure if the table is generated by a script and edited by hand. A monotonicity check at startup over, say, 256 entries costs microseconds once and catches a corrupt flash image or a bad update before the control loop trusts it.

Overflow: lo + hi overflows size_t only for enormous tables, but dy * (raw - lo_raw) overflows 32-bit easily. With dy up to 2^31 and a raw delta up to 65535, the product needs 64-bit. On a Cortex-M4 without an FPU, that 64-bit divide is the expensive part, roughly tens of cycles, still trivial at 1 kHz. If I needed it faster I would precompute a slope per segment in fixed point and replace the divide with a multiply, accepting rounding error I can bound.

NaN and fault codes: with integer ADC codes this does not arise, but if the input comes from a float sensor library, a NaN makes every comparison false and the search walks to an arbitrary bracket. I reject non-finite inputs before the search.

Why not linear scan

For 1024 entries, linear scan averages 512 comparisons and worst case 1024, each a flash read. Binary search needs 10. At 1 kHz that difference is the difference between a loop that finishes in a few microseconds every time and one whose timing varies with the input, which complicates jitter analysis for the rest of the loop. Linear scan only wins for tiny tables, under about 8 entries, where the branch mispredicts of binary search cost more than the extra reads, or where the table is rebuilt often and cannot be kept sorted.

The invariant t[lo].raw <= raw < t[hi].raw is what I would defend in review. Every branch preserves it, the loop terminates because hi - lo shrinks each iteration, and the exit condition hands interpolation a valid pair with dx > 0 provided the table passed its monotonicity check.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-54How does a binary min-heap schedule the next due task when you have many periodic sensors?

The 90-second answer

Keep every periodic sensor task in a binary min-heap keyed by its next deadline, with sensor id as the tie break. The earliest deadline is always at the root, index 0, so the scheduler peeks at it in O(1) and only pays O(log n) when a task runs and is reinserted with its new deadline. With 64 sensors that is at most 6 comparisons to restore the heap, instead of scanning all 64 tasks on every tick to find the one that is due.

C
// Checked against C11. Ticks are uint32_t milliseconds.
typedef struct {
    uint32_t next_due;  // heap key
    uint32_t period;    // ms
    uint8_t  id;
} SensorTask;

#define MAX_SENSORS 64
static SensorTask heap[MAX_SENSORS];
static int heap_n;

static int task_less(const SensorTask *a, const SensorTask *b) {
    if (a->next_due != b->next_due) return a->next_due < b->next_due;
    return a->id < b->id;
}

static void sift_up(int i) {
    while (i > 0) {
        int p = (i - 1) / 2;
        if (!task_less(&heap[i], &heap[p])) break;
        SensorTask t = heap[p]; heap[p] = heap[i]; heap[i] = t;
        i = p;
    }
}

static void sift_down(int i) {
    for (;;) {
        int l = 2 * i + 1, r = l + 1, m = i;
        if (l < heap_n && task_less(&heap[l], &heap[m])) m = l;
        if (r < heap_n && task_less(&heap[r], &heap[m])) m = r;
        if (m == i) break;
        SensorTask t = heap[m]; heap[m] = heap[i]; heap[i] = t;
        i = m;
    }
}

void scheduler_tick(uint32_t now) {
    while (heap_n > 0 && (int32_t)(now - heap[0].next_due) >= 0) {
        SensorTask t = heap[0];
        run_sensor(t.id);
        t.next_due += t.period;  // anchor to old deadline, not now
        heap[0] = t;
        sift_down(0);
    }
}

The heap invariant is the whole trick. For every parent at index i, its children at 2*i+1 and 2*i+2 are greater than or equal to it under task_less. That does not sort the whole array. It only guarantees the minimum sits at the root, which is all the scheduler needs to decide what runs next.

Worked trace

Four sensors start at now = 0: id 0 every 10 ms, id 1 every 50 ms, id 2 every 100 ms, id 3 every 20 ms. Initial next_due equals the period, so the heap array is [id0:10, id3:20, id1:50, id2:100].

now (ms)Root before runActionRoot after reschedule
10id0 due 10run id0, next due 20id0 due 20 (tie with id3, lower id wins)
20id0 due 20run id0, next due 30id3 due 20
20id3 due 20run id3, next due 40id0 due 30
30id0 due 30run id0, next due 40id0 due 40 (tie with id3, lower id wins)
40id0 due 40run id0, next due 50id3 due 40
40id3 due 40run id3, next due 60id0 due 50
50id0 due 50run id0, next due 60id1 due 50

Each step touches only the root and one path down the tree. No scan of the other sensors happens. The while loop in scheduler_tick handles the two runs at now = 20 and at now = 40 without a second tick.

Why not a sorted list or a scan

ApproachFind next dueInsert or rescheduleCost at 64 sensors
Scan all tasks each tickO(n)O(1)64 comparisons per tick, every tick
Sorted arrayO(1) at headO(n) shiftup to 63 moves per reschedule
Binary min-heapO(1) at rootO(log n) siftat most 6 swaps per reschedule

The scan looks simpler and wins for 3 or 4 tasks. Past roughly a dozen periodic tasks the heap wins because rescheduling happens constantly while the tick check happens even more often.

Failure modes worth naming

Tick wraparound breaks a plain now >= next_due test after 49.7 days on a 32-bit millisecond counter. The code above casts the difference to int32_t, which stays correct as long as no deadline is more than about 24 days in the future. Mutating next_due in place without sifting breaks the invariant silently, so the field should only be written through the heap functions. Adding the period to now instead of to the old deadline causes drift under load: a task delayed 3 ms by a higher priority interrupt runs 3 ms late forever. Anchoring to the old deadline keeps the long term rate exact, at the cost of catching up in a burst if the system was blocked for several periods. For sensor sampling that burst is usually wrong, so cap catch up at one run and skip the missed periods.

Equal deadlines need the id tie break shown in task_less. Without it, heap order between equal keys is unspecified and the trace above would not be reproducible in a test.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-55Your 32-bit millisecond tick wraps every 49.7 days, so how do you compare timestamps and timeouts correctly across the wrap without using signed arithmetic?

The 90-second answer

Use unsigned 32-bit ticks and never compare two timestamps directly with < or >. Compare a difference. Unsigned arithmetic in C is defined modulo 2^32, so subtraction gives the correct elapsed time even when the counter has wrapped, provided the true interval is less than half the range.

For a 1 ms tick, 2^32 ms is 4,294,967,296 ms, about 49.71 days. Half of that is 2^31 ms, about 24.86 days. That is the limit. If you only ever compare events within 24.86 days of each other, which covers timeouts, debounce windows, sensor ages and scheduling deadlines, the wrap disappears.

C
#include <stdint.h>

static inline uint32_t elapsed_ms(uint32_t now, uint32_t then)
{
    return now - then; /* modulo 2^32, defined for unsigned */
}

/* true if now has reached or passed deadline, assuming the
   deadline is within 2^31 ms of now */
static inline int expired(uint32_t now, uint32_t deadline)
{
    return (int32_t)(now - deadline) >= 0;
}

/* portable form without relying on the signed conversion */
static inline int expired_portable(uint32_t now, uint32_t deadline)
{
    return ((now - deadline) & 0x80000000u) == 0u;
}

The signed cast works because the low 32 bits are reinterpreted as two's complement. A difference of 0 to 2^31-1 stays positive, and a difference that is really negative, meaning now is before deadline, has the top bit set. On current mainstream C, where two's complement is the norm and C23 mandates it, that cast is predictable. The portable form above makes the same test on the unsigned result and avoids depending on it.

Worked trace across the wrap

Suppose a task started at then = 0xFFFFFF00 and the tick has since wrapped to now = 0x00000100.

ValueHexDecimalMeaning
then0xFFFFFF004,294,967,040start, 256 ms before wrap
wrap point0x000000000counter rolls over
now0x00000100256256 ms after wrap
now - then0x00000200512elapsed, correct despite now < then
(int32_t)(now - then)0x00000200512positive, so then is in the past

A direct test now > then would say the start is in the future. The subtraction test does not.

The same pattern handles a deadline set in the future. Set deadline = now + 1000 at now = 0xFFFFFFF0. The deadline becomes 0x000003E8 after the wrap. At now = 0x00000100, now - deadline is 0xFFFFFD18, whose top bit is set, so expired() returns false. At now = 0x000003E8, the difference is zero and it returns true. At now = 0x00000400, the difference is 24 and it stays true until the comparison window itself expires.

Where it breaks

The failure mode is an interval at or beyond 2^31 ms. A difference of exactly 2^31 ms has the top bit set and looks negative. You cannot distinguish "24.86 days ago" from "24.86 days in the future" with 32 bits alone. That is not a bug you can code around. If a log, a certificate expiry or a user-visible timestamp can be compared over longer spans, use a 64-bit monotonic counter, widen the tick to 64 bits on wake, or store a wrap count alongside the 32-bit value and compare the pair.

Two other traps show up in firmware. First, mixing signed tick variables into the arithmetic. If now is int32_t, the subtraction can overflow, which is undefined behaviour in C, and the compiler is free to optimise the check away. Keep every tick, deadline and elapsed value uint32_t until the final sign test. Second, a tick that can jump, such as a wall clock corrected by NTP or a tick that stops in Stop mode, breaks the assumption that time only moves forward by small steps. Use a monotonic hardware timer for timeouts and keep wall time separate.

In a review I would ask for the half-range bound to be stated next to the helper, a unit test that sets then just before 0xFFFFFFFF and now just after zero, and a grep for any remaining tick > deadline comparisons. Those three things catch almost every wrap bug I have seen in production firmware.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-56A 16-bit tick at 1 kHz wraps every 65 seconds. How do you write a 100 ms timeout check that still works after the wrap, and when would you widen the counter instead?

The 90-second answer

Keep the tick unsigned and compare elapsed time, not absolute tick values. Store the tick when the operation starts, subtract it from the current tick using unsigned arithmetic, and compare the result with the timeout. Unsigned subtraction in C wraps modulo 2^16 for a uint16_t, so the result stays correct after the counter rolls from 65535 to 0, as long as the timeout is shorter than half the counter range.

C
#include <stdint.h>
#include <stdbool.h>

static inline bool timed_out(uint16_t now, uint16_t start, uint16_t timeout)
{
    return (uint16_t)(now - start) >= timeout;
}

/* Usage at 1 kHz, 100 ms timeout */
uint16_t start = tick;
while (!timed_out(tick, start, 100)) {
    /* poll or wait */
}

A direct test such as now >= start + 100 fails near the wrap. If start is 65500, start + 100 wraps to 64, and the comparison treats almost every later tick as already expired.

Worked trace

Start at 65500, timeout 100 ticks:

nownow - starttimed_outResult
655000falsejust started
6553535false35 ms elapsed
036falsewrapped, 36 ms elapsed
6399false99 ms elapsed
64100truetimeout fires
200236truestill expired

The subtraction produces 36 at now == 0 because 0 minus 65500 modulo 65536 equals 36. That is the whole mechanism. No special wrap branch is needed.

Why signed arithmetic is the trap

Signed overflow in C is undefined behaviour. The compiler may assume start + timeout never overflows and simplify the comparison in a way that breaks after wrap. Unsigned overflow is defined, so the optimiser must preserve the modulo behaviour. This is also why casting the tick to int16_t to make a comparison look natural is unsafe. The conversion and the subsequent subtraction can overflow signed range.

When subtraction is enough and when to widen

ApproachWhat it fixesCost and limit
Unsigned subtraction on uint16_tTimeouts and intervals under 32768 ticks, about 32.7 s at 1 kHzNo extra RAM, but intervals at or above half the range are ambiguous
Widen to uint32_t at 1 kHzWrap moves to 49.7 days, intervals up to about 24.8 days stay unambiguous2 extra bytes per timestamp, still wraps eventually
Widen to uint64_tWrap is not a practical concern at 1 kHz8 bytes per timestamp, wider arithmetic on a 32-bit core, awkward in logs and wire formats

For a 100 ms timeout, subtraction on the existing 16-bit tick is the right fix. Widening buys nothing for that job and costs RAM and code size.

Widen when the value is a timestamp that must remain ordered or unique for longer than the wrap period. A 16-bit tick at 1 kHz repeats every 65.5 s, so two events 70 s apart can share the same raw value. If those values go into a log, a file, or a protocol, a reader cannot tell them apart. A 32-bit tick repeats every 49.7 days at 1 kHz, which suits most products that reboot at least monthly. If the device must run for years without a reboot and timestamps must stay unambiguous, use a 64-bit tick or pair the 32-bit tick with a wrap count incremented in the overflow interrupt.

Limits to state out loud

The subtraction idiom only works while the measured interval stays below half the counter range. A 40 s timeout on a 16-bit 1 kHz tick exceeds 32768 ticks, so the elapsed value becomes ambiguous and the check can fire early or never. The fix there is a wider counter or a periodic re-arm, not a different comparison.

Also keep timeouts on the monotonic tick and wall clock time separate. Adding an epoch offset to the tick gives a calendar timestamp that drifts with oscillator tolerance, often tens of parts per million, and jumps when the clock is corrected. Use the tick for ordering and deadlines, and record the wall clock alongside it when correlation with external time matters.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-57Your Cortex-M device gets firmware updates over BLE from an untrusted phone. How would you choose between signing the image and encrypting it with AES-GCM, and where would you keep the keys?

The 90-second answer

Sign the image first. A signature proves the image came from your build server and was not changed in transit, and the device only needs your public key to check it. AES-GCM proves the same integrity, but it also needs a secret key on every device. If one device is read out, that key can be used to forge updates for all of them. Use GCM only when you also need confidentiality, for example when the firmware itself is valuable IP and the BLE link or flash could be read by a third party.

Assume updates arrive over BLE from a phone you do not trust, the bootloader runs on a Cortex-M4 or M33, and the application uses A/B slots. The phone can drop, reorder or modify packets. It cannot be trusted to deliver the right bytes.

ApproachWhat the device checksKey on deviceMain risk
Ed25519 or ECDSA P-256 signatureSignature over the whole image verifies with a public keyPublic key, 32 to 64 bytesPrivate key leak at the signer, replay of an old signed image
AES-GCM encryptionTag verifies with a shared secret, plaintext stays hiddenSecret key, 16 or 32 bytesKey extraction from one device, nonce reuse
Signature plus GCMBoth checks, in that orderPublic key plus secret keyBoth risks, plus more code and flash

The nonce point is the one interviewers probe. GCM is safe only if a nonce is never reused with the same key. Reuse leaks the authentication key and lets an attacker forge tags. Do not use a counter stored in flash as the nonce, because a power cut can roll it back. Generate a random 96-bit nonce per image on the signer and send it with the package.

C
/* Signer: random nonce, header bound as associated data */
uint8_t nonce[12];
rand_bytes(nonce, sizeof(nonce));
/* AAD = magic || version || image_len || model_id */
aes_gcm_encrypt(key, nonce, aad, aad_len,
                image, image_len, ciphertext, tag);
/* Package = nonce || tag || ciphertext, then sign the package */
ed25519_sign(signing_key, package, package_len, signature);

On the device, verify before you decrypt or write anything. Acting on unauthenticated plaintext, even to a staging slot, invites faults you do not need.

C
int stage_update(const uint8_t *pkg, size_t len,
                 const uint8_t *sig, uint32_t version) {
    if (!ed25519_verify(boot_pubkey, pkg, len, sig)) return -1;
    if (version <= installed_version) return -1; /* replay */
    if (aes_gcm_decrypt(dev_key, nonce, aad, aad_len,
                        ciphertext, len, tag, plain) != 0) return -1;
    write_inactive_slot(plain, plain_len);
    mark_slot_pending();
    return 0;
}

Key storage follows from who must be trusted. Keep the signing private key off the device entirely, in an HSM or a locked build machine. Burn the public key into the bootloader, ideally hashed into OTP or eFuse on parts that support it, and lock debug access so it cannot be swapped. For GCM, never put a fleet-wide key in application flash. Use a per-device key generated inside a secure element such as an ATECC608, or in TrustZone secure storage on an M33, and derive it from a master key that never leaves that hardware. One extracted device then compromises only itself.

fail pass Receive package over BLE Verify signature Discard package Decrypt if GCM is used Write inactive slot Reboot and confirm, else roll back

Replay needs a separate check. A valid signature on version 12 does not stop an attacker replaying version 11 with a known bug. Store the lowest accepted version in a counter the bootloader increments only after the new slot boots successfully, in OTP, a secure element, or a dedicated flash sector. Test power cuts during staging and during first boot. Both must leave the device on the last confirmed image.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-58What must match the OTP fuse value before the ROM bootloader verifies a firmware signature?

The 90-second answer

The ROM bootloader hashes the public key carried in the firmware image and compares that hash with the hash burned into OTP fuses at the factory. Only if the two hashes match does it verify the firmware signature with that public key. Unsigned firmware has no valid signature for that key, so verification fails and the ROM does not jump to it.

OTP fuses are one-time programmable. They can be written once and cannot be erased in the field, so an attacker who can rewrite flash cannot replace the trusted hash.

No Yes No Yes ROM bootloader starts Read key hash from OTP fuses Hash public key in image header Hashes equal? Do not boot image Verify signature with that public key Signature valid? Boot firmware

Why a hash, not the key itself

A SHA-256 hash is 32 bytes. A 2048-bit RSA public key is about 256 bytes and an ECDSA P-256 public key is 65 bytes. Storing the hash uses fewer fuses. The full public key can stay in the signed image header, where flash space is cheaper, because the ROM only trusts it after its hash matches the fuse value.

That order matters. If the ROM verified a signature with whatever key the image supplied, an attacker would supply their own key and sign with their own private key. The hash comparison stops that substitution before signature verification runs.

C
/* C, pseudocode for the ROM check */
bool boot_image(const image_t *img)
{
    uint8_t digest[32];
    uint8_t fuse_hash[32];

    otp_read_key_hash(fuse_hash);
    sha256(img->public_key, img->key_len, digest);

    if (memcmp(digest, fuse_hash, 32) != 0) {
        return false;
    }
    return verify_signature(img->public_key, img->signature,
                            img->payload, img->payload_len);
}
Image presentedKey hash matches fuseSignature verifiesROM action
Signed vendor firmwareYesYesBoots
Vendor firmware with altered payloadYesNoDoes not boot
Attacker firmware signed with attacker keyNoYes, under attacker keyDoes not boot
Unsigned firmwareYes or noNo signature to verifyDoes not boot

Limits of the check

Burning the wrong hash at the factory bricks that unit, because the fuse cannot be corrected. Vendors therefore test the flow on engineering samples before committing the production hash.

The check also depends on keeping the vendor private key secret. If that key leaks, signatures made with it will pass both checks. Some SoCs add a revocation fuse or a key version counter so a compromised key can be retired, but the basic rule stays the same: no matching fuse hash, no signature check, no boot.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-59How does a monotonic anti-rollback counter in the bootloader stop an attacker replaying signed but vulnerable firmware v12 after you ship v15, and where does that design break?

The 90-second answer

The version is inside the signed image, and the bootloader compares it against a counter the application cannot decrement. Ship v15, burn 15 into one-time storage, and a replayed v12 image fails the check image_version >= stored_version even though its signature still verifies. The signature proves who built v12. The counter proves v12 is no longer acceptable.

That only works if the counter lives outside normal flash. On STM32H7 and i.MX RT parts I use eFuse or OTP bits, or a secure element counter, programmed by the bootloader after a successful trial boot. A counter in a flash sector the application can erase is just a variable an attacker with a debug probe or a compromised update path can reset.

How the check runs

C
/* Bootloader, checked against C11, image header parsed from flash */
typedef struct {
    uint32_t version;      /* monotonic, e.g. 15 for release 15 */
    uint32_t image_len;
    uint8_t  signature[64]; /* Ed25519 over header + image */
} image_header_t;

bool boot_image(const image_header_t *h, uint32_t stored_min)
{
    if (h->version < stored_min) return false;   /* replay */
    if (!verify_signature(h)) return false;      /* tampered */
    return true;
}

The increment is the delicate part. Incrementing before the new image boots bricks the device if that image crashes. So the bootloader boots the candidate in a trial state, the application confirms itself after its own self-tests pass, and only then asks the bootloader to commit the new minimum. A power cut before commit leaves the old minimum in place and the device can still fall back to the previous slot. A power cut after commit is safe because the new image already ran.

no yes no yes yes no Bootloader reads header Signature valid? Reject, boot fallback slot version >= stored_min? Trial boot candidate App confirms after self-test? Burn stored_min = version

Worked trace

Assume stored_min = 12 at first boot, and each release bumps the version by one.

EventImage versionstored_min beforeDecisionstored_min after
Install v13131213 >= 12, signature ok, trial boot ok13
Install v15151315 >= 13, signature ok, trial boot ok15
Attacker replays v12121512 < 15, reject before signature check matters15
Attacker replays v151515Accepted, it is the current release15
Attacker edits v15 header to 999915Signature fails, reject15

The last two rows show the boundary. Anti-rollback stops going backwards. It does not stop reinstalling the current version, and it does not replace the signature. Both checks are needed, and the version comparison is cheap enough to do first.

Where it breaks in practice

Flash-based counters fail first. If you store the minimum in a flash page and update it with erase and rewrite, a torn write during power loss can leave the page erased, which many bootloaders read as zero. I have seen a design where that silently reset the minimum to zero and reopened every old vulnerability. OTP avoids the torn write, but OTP bits are finite. A 32-bit eFuse counter at one increment per release lasts decades. A design that increments on every boot attempt, or that burns one bit per increment in a unary scheme with only 32 bits, runs out in a few years of field updates. Check the part manual for how many OTP words you actually get, not the marketing number.

Recovery and debug paths are the second hole. If a UART recovery mode accepts an unsigned image, or SWD can reprogram the counter, the attacker does not need to defeat the check. They use the other door. On production parts I disable debug or require a signed, authenticated unlock, and the recovery loader runs the same version check as the main bootloader.

Third, the counter must be bound to the device or at least to the product line. A version number that is global across a product family lets an attacker take a signed image built for a cheaper variant with weaker hardware and replay it on a higher variant if the signature key is shared. Signing the version together with a product ID or hardware revision in the header closes that, because the signature then covers the binding.

Fourth, do not let the application increment the counter directly. The application should request a commit, and the bootloader should re-verify the image and the trial boot flag before burning. Otherwise a bug in the application, or a compromised application, can burn the counter to the maximum value and brick every future update. That failure is permanent on OTP, which is why the commit path needs the same care as the verification path.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-60How would you store a device signing key in a secure element or TrustZone instead of application flash, and keep it usable without ever exporting it?

The 90-second answer

Generate the key inside the secure element or the TrustZone secure partition, mark it non-exportable, and only ever ask that boundary to sign or decrypt. Application code holds a handle or slot number, never the bytes. If the application flash is dumped over SWD or read from a removed chip, there is no private key to recover.

That changes the API. You do not call export_key() and then sign in the app. You send a digest in and get a signature out. With PSA Crypto on a Cortex-M33 running Trusted Firmware-M, that looks like this:

C
/* key_handle was created by the secure partition at provisioning.
   PSA_KEY_USAGE_SIGN_HASH is set, PSA_KEY_USAGE_EXPORT is not. */
uint8_t digest[32]; /* SHA-256 of the payload */
uint8_t sig[64];    /* raw r||s for P-256 */
size_t sig_len = 0;

psa_status_t st = psa_sign_hash(
    key_handle,
    PSA_ALG_ECDSA(PSA_ALG_SHA_256),
    digest, sizeof(digest),
    sig, sizeof(sig), &sig_len);
if (st != PSA_SUCCESS) {
    handle_crypto_error(st); /* key locked, slot invalid, SE busy */
}

The same pattern works with a discrete secure element such as a Microchip ATECC608. The private key lives in a configured slot, the host sends a SIGN command with the digest over I2C or SWI, and the device returns the signature. The host never sees the key material.

Secure element, TrustZone, or flash: what actually differs

PropertyKey in app flashKey in TrustZone-M secure partitionKey in discrete secure element
Where key bytes liveSame flash as firmware, often readable with debug or chip-offSecure flash and SRAM, inaccessible to non-secure code when SAU and IDAU are configured correctlySeparate die, key generated on chip and never leaves it
How app uses itReads bytes, signs in softwareCalls PSA Crypto through a secure partition, gets signature backSends command over I2C/SWI, gets signature back
Main costNoneNeeds a TrustZone-capable MCU, secure boot chain, and partition maintenanceExtra BOM, I2C bus traffic, sign latency, second supply chain
Main riskOne debug readout or flash dump exposes every device key if sharedMisconfigured non-secure callable or debug port leaks the partitionBus sniffing, replay, or a slot configured as exportable

TrustZone keeps everything on one chip and usually signs faster, because there is no external bus round trip. A secure element gives stronger isolation. Even a compromised main SoC, including its secure partition if that code has a bug, does not automatically expose the key. It also survives a main chip swap only if you re-provision, which is a manufacturing decision to make early.

Figures you can defend in the room

A P-256 private key is 32 bytes. Its raw signature is 64 bytes, r||s, and 70 to 72 bytes when DER encoded. An ATECC608 has 16 slots, of which 8 (slots 8 to 15) can hold P-256 private keys, so one chip can hold a device identity key, a firmware signing key, and spares without running out. An ECC sign on that part takes roughly 50 to 115 ms depending on voltage and temperature, plus a few milliseconds for the I2C transaction at 100 kHz. That caps you near 8 to 20 signs per second, which is fine for a TLS handshake or a once-per-minute attestation and useless for signing every sensor sample.

On a Cortex-M33 at 160 MHz with a hardware accelerator, a PSA P-256 sign is typically in the low single-digit milliseconds. In software without an accelerator, budget 10 to 30 ms. Either way it is an order of magnitude faster than the secure element, and it does not block the I2C bus. The trade is isolation: a bug in your secure partition, or a non-secure callable that returns raw key bytes, undoes the benefit, while the secure element keeps the key on a separate die even if the host firmware is fully compromised.

Provisioning and the failure modes that matter

Provisioning decides whether the design holds. Generate the key on the device, in the secure element or secure partition, and export only the public key. If you generate the key on a PC and inject it, the PC, the test fixture, and every log file become part of the trusted base. For per-device identity, generate on chip and certify the public key with a factory CA, so the server can verify the signature and know the key was born on genuine hardware.

Configure the slot or PSA key attributes before you load anything sensitive. On a secure element, that means setting the slot as private, disabling export, and locking the configuration. On TrustZone, it means the key attributes must exclude export, the secure partition must not expose a raw export service to non-secure callers, and debug must be disabled or authenticated in production lifecycle. A key that is technically in TrustZone but reachable through a non-secure callable that returns raw bytes is just flash with extra steps.

Three failures show up in review. First, the I2C link to a secure element is plaintext. An attacker with a logic analyser can capture digests and signatures and replay them, so sign a fresh challenge from the server rather than a static payload, and include a nonce or counter in the signed data. Second, debug and test modes. If SWD, JTAG, or the secure element test mode stays enabled after manufacturing, isolation is theoretical. Lock lifecycle state and verify the lock on the production line. Third, no rotation path. If a key is compromised or a slot is misconfigured, you need a way to retire it. That means a key version in the signed payload, a server-side allowlist of valid public keys, and a documented re-provisioning flow, not a firmware update that tries to extract the old key.

psa_sign_hash(handle, digest) signature only signature only I2C SIGN command with digest signature only Non-secure app PSA Crypto / secure partition TrustZone secure SRAM and flash Secure element

Pick TrustZone when the MCU already supports it and the team can maintain the secure partition and boot chain. Pick a secure element when the threat model includes a compromised or buggy main firmware, or when you need certified key storage the main chip cannot provide. In both cases the test is simple: dump the application flash, dump the non-secure flash, and confirm you still cannot produce a valid signature without going through the secure boundary.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-61How do you disable SWD and JTAG on a Cortex-M in production without losing the ability to diagnose a field failure?

The 90-second answer

Lock the debug port at provisioning time, not in application code, and replace the debugger with a log the device writes itself. On STM32F4 that means Readout Protection Level 1 in the option bytes, programmed by the factory jig after functional test. The application then records faults, resets and watchdog expiries to a CRC protected ring in flash. A field return is diagnosed by reading that log through an authenticated command channel, or by a signed unlock token the bootloader checks, never by leaving SWD open.

What locking actually does

RDP Level 0 leaves flash readable over SWD. Level 1 blocks flash and SRAM readout and blocks programming unless the chip is mass erased, which wipes the log. On STM32F4 Level 1 also disables debug access. Level 2 also blocks boot from SRAM and cannot be reversed without destroying the device, so it is wrong for a product that must be diagnosed. Some newer families, such as STM32G0, STM32L4 and STM32H5, add a separate option byte to disable the debug port or the SWD pins. Where that byte exists, set it in the same provisioning step. Where it does not, RDP Level 1 is the lock.

Two bits are often mistaken for a lock. C_DEBUGEN in DHCSR is written by the debugger to request halting debug. Clearing it from application code does not stop a probe attaching later, because the probe can set it again. DBGMCU on STM32F4 controls whether the core halts in Sleep, Stop and Standby and whether trace is enabled. It does not disable the SWD or JTAG pins. Neither bit is a security boundary.

C
/* Provisioning jig only, STM32F4 HAL. Never called from the app. */
FLASH_OBProgramInitTypeDef ob = {0};
ob.OptionType = OPTIONBYTE_RDP | OPTIONBYTE_USER;
ob.RDPLevel = OB_RDP_LEVEL_1;
ob.USERConfig = OB_IWDG_SW | OB_STOP_IWDG | OB_STANDBY_IWDG;
HAL_FLASH_OB_Unlock();
HAL_FLASH_OBProgram(&ob);
HAL_FLASH_OB_Launch(); /* resets the chip, RDP1 now active */

Run the full self test before this step. A chip locked at RDP1 with a dead I2C sensor or a bad clock tree cannot be recovered except by mass erase, and the erase destroys the evidence.

MechanismBlocksReversibleCost if misused
RDP Level 1Flash and SRAM readout, programming and debug on STM32F4Only by mass eraseLog and calibration lost on erase
RDP Level 2Debug plus SRAM bootNoPermanent loss of debug
Debug disable option byte, where fittedSWD and JTAG accessOnly by option byte change, if the family allows itNo diagnosis if the log is RAM only
C_DEBUGEN cleared in DHCSRNothing persistentYes, by any probeFalse sense of security

Keeping diagnosis without a probe

Store a fixed size record on every HardFault, watchdog reset, brown out and failed self test: fault status registers, stacked PC and LR, a monotonic boot counter, uptime, last sensor error and a CRC. Keep 64 records of 32 bytes in two flash pages, 2 KB total, written in a journal so a power cut mid write leaves the previous record intact. The fault handler copies the stacked frame, writes the record, then resets. It must not call printf, malloc or a mutex. The watchdog handler does the same through a flag in a no init section that survives reset.

C
typedef struct __attribute__((packed)) {
    uint32_t magic;      /* 0x464C4F47 */
    uint32_t boot_count;
    uint32_t fault_cfsr;
    uint32_t fault_bfar;
    uint32_t pc;
    uint32_t lr;
    uint32_t uptime_ms;
    uint16_t crc16;
    uint16_t reserved;
} fault_record_t; /* 32 bytes */
Fault or watchdog reset Handler copies stacked frame Write record plus CRC to flash journal Reset to bootloader Bootloader checks image, boots app App reports log over authenticated channel Signed token may enable SWD for one session

Field access

Prefer reading the log over the product interface, UART or BLE, gated by a challenge response. The device sends a nonce, the service tool returns an HMAC or signature made with a per device key held in a secure element or TrustZone, and only then does the device dump records. That gives diagnosis with no debug port at all. If a bench session truly needs SWD, the bootloader can accept a signed unlock blob, verify it against a public key in OTP, enable SWD for that boot only, and record the unlock in the log. An unsigned or replayed blob is rejected, and the monotonic counter stops reuse of an old token.

Two failure modes dominate. First, writing the log on every fault without wear levelling wears the page. At one fault per day that is fine, at a fault loop resetting every second it is not, so rate limit records and count suppressed faults in RAM. Second, enabling SWD in application code with a simple UART command gives any attacker the same path. Keep the unlock check in the bootloader, keep the private key off the device, and test the locked build on the bench before the jig locks the first production batch.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-62How would you design factory provisioning so each device gets its own unique key and no shared secret ships?

The 90-second answer

Generate the key outside the device, inject it once on a wired factory jig, and store it where application code cannot read it back in plaintext. A provisioning server backed by an HSM creates a fresh 256-bit key per serial number with a CSPRNG. The jig talks to the device over UART or SWD on a closed bench, the device writes the key into OTP, a secure element, or an encrypted flash partition, reads it back, and only then reports success. The server records serial number plus the SHA-256 fingerprint of the key. It never records the key itself.

That shape gives three properties an interviewer will probe. Uniqueness comes from generation per device, so a leak from one unit does not compromise the fleet. Confidentiality comes from storage, so a firmware bug or a dumped application image does not expose it. Auditability comes from the fingerprint log, so you can prove a serial was provisioned without keeping a database of live secrets.

Frame format, checked against C11 on a Cortex-M4: byte 0 is magic 0xA5, byte 1 is version 0x01, bytes 2 to 5 are the serial number in little endian, bytes 6 to 37 are the 32 byte key, and the final 4 bytes are CRC-32 IEEE of all preceding bytes, stored little endian. Total length is therefore 42 bytes.

C
/* Provisioning mode, C11, Cortex-M4. */
#include <stdint.h>
#include <stddef.h>
#include <string.h>

#define KEY_LEN 32u
#define FRAME_LEN (6u + KEY_LEN + 4u)
#define FRAME_MAGIC 0xA5u
#define FRAME_VERSION 0x01u

typedef enum { PROV_OK = 0, PROV_BAD_LEN, PROV_BAD_HEADER, PROV_BAD_CRC, PROV_MISMATCH } prov_status_t;

uint32_t crc32_ieee(const uint8_t *data, size_t len);
int secure_store_write(uint32_t slot, const uint8_t *data, size_t len);
int secure_store_read(uint32_t slot, uint8_t *data, size_t len);

static uint32_t load_u32_le(const uint8_t *p)
{
    return ((uint32_t)p[0]) | ((uint32_t)p[1] << 8) |
           ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}

static void secure_wipe(void *p, size_t len)
{
    volatile uint8_t *v = (volatile uint8_t *)p;
    while (len--) { *v++ = 0; }
}

prov_status_t provision_key(const uint8_t *frame, size_t len, uint32_t expected_serial)
{
    uint8_t verify[KEY_LEN];
    prov_status_t rc;

    if (len != FRAME_LEN) { return PROV_BAD_LEN; }
    if (frame[0] != FRAME_MAGIC || frame[1] != FRAME_VERSION) { return PROV_BAD_HEADER; }
    if (load_u32_le(frame + 2) != expected_serial) { return PROV_BAD_HEADER; }
    if (crc32_ieee(frame, FRAME_LEN - 4u) != load_u32_le(frame + FRAME_LEN - 4u)) {
        return PROV_BAD_CRC;
    }
    if (secure_store_write(0u, frame + 6, KEY_LEN) != 0) { return PROV_MISMATCH; }
    if (secure_store_read(0u, verify, KEY_LEN) != 0 || memcmp(verify, frame + 6, KEY_LEN) != 0) {
        rc = PROV_MISMATCH;
    } else {
        rc = PROV_OK;
    }
    secure_wipe(verify, sizeof(verify));
    return rc;
}

The jig sends one frame as defined above. The device rejects a wrong length, magic, version, or serial before touching storage, and rejects a bad CRC before touching storage. After the write it reads back through the same secure store path the application will use, compares all 32 bytes, and replies with status plus the fingerprint. Only a PROV_OK reply lets the jig advance the unit to the next station.

HSM generates 256-bit key Jig sends key plus serial over wired link Device checks CRC and serial Write to OTP or secure element Read back and compare Reply with fingerprint Server logs serial and fingerprint
StepWhat happensFailure it catches
GenerateHSM creates 32 random bytes for this serialShared default key across the fleet
TransferJig sends 42 byte frame over UART at 115200 baud, CRC-32 checkedTruncated or corrupted write on a noisy bench
StoreKey lands in OTP, secure element, or encrypted partitionKey readable from a firmware dump
VerifyDevice reads back and compares byte for byteSilent flash write failure
LogServer stores serial and SHA-256 fingerprintDuplicate provisioning of the same unit
LockDebug port disabled, provisioning command removedKey extraction after the device leaves the factory

Failure modes worth naming. Power loss mid-write is the classic one. OTP and secure elements usually write atomically per slot, but flash partitions do not. I would write to an empty slot, verify it, and only then mark the slot valid with a separate commit flag. A unit that loses power before the commit flag is set gets reprovisioned from scratch. A unit that loses power after the commit flag is set keeps its key.

Duplicate injection is the second one. If an operator runs the same unit through the jig twice, the second run must either refuse or produce a logged rekey event. Refusing is safer for a first production run. It forces a human to investigate instead of silently replacing a key that may already be registered with the cloud backend.

The third failure is leakage through the bench itself. Jig logs, screenshots, and test reports often capture everything the device prints. The device should print the fingerprint and status only. The raw key should never appear on UART, in a log file, or in a test report. Debug builds that echo the key must be excluded from production firmware, and the provisioning command handler should be compiled out or locked behind a fuse after the final test.

Alternatives and when they fit. Deriving per-device keys from a master key with HKDF is cheaper on the bench because the device only needs the master key once. It also means one master key compromise breaks every device ever shipped, so I would only use it with the master key held in an HSM and the derivation done server side. A secure element that generates the key internally and never exports it is stronger still, and it suits high value devices where the element cost is acceptable. For a cost sensitive product, injecting a generated key into OTP on the main MCU is the usual compromise.

What I would check before calling the line ready. Provision 100 units, confirm all fingerprints differ, confirm a duplicate run is refused, pull power at random points during the write and confirm no unit boots with a half written key, and try reading the key slot from application firmware. If any of those checks fail, the design is not done, however clean the happy path looks.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-63Power drops halfway through a flash page write of your config log. How do you use journaling and CRC so reboot recovers the last committed value and never a torn one?

The 90-second answer

Never update the only copy in place. Keep two flash pages, A and B, each holding a journal of fixed-size records. A record is written with its commit field left erased, its CRC computed over sequence, length and payload, and the commit field programmed last as a single word. On boot I scan both pages, accept only records whose CRC matches and whose commit word is present, and replay the highest valid sequence. A torn write fails CRC or lacks the commit word, so it is ignored and the previous committed value survives.

Assume NOR flash, for example STM32 internal flash with 1 to 2 KB pages, program time around 0.5 ms per word and erase 50 to 150 ms per page. Those numbers matter because the vulnerable windows are the erase and the final commit program, not the bulk payload write.

Record layout and write order

C
/* Checked against C11. Record is 32 bytes, one flash word is 4 bytes. */
#define COMMIT_WORD 0xA5A5A5A5u
#define ERASED_WORD 0xFFFFFFFFu

typedef struct __attribute__((packed)) {
    uint32_t seq;        /* monotonic, never reused within a page generation */
    uint16_t len;        /* payload length, <= 16 */
    uint16_t crc16;      /* CRC-16/CCITT over seq, len, payload */
    uint8_t  payload[16];
    uint32_t commit;     /* programmed last, ERASED_WORD until committed */
} record_t;              /* 28 bytes, padded to 32 in the journal */

Write path, with interrupts and DMA quiesced for the config task:

  1. Pick the inactive page. It must already be erased. If not, erase it now, while the active page still holds the last committed state. Power loss during this erase destroys nothing live.
  2. Program payload, header and CRC with commit still 0xFFFFFFFF. NOR can only clear bits, so this order is legal.
  3. Read back and verify CRC in RAM. This catches a failed program before commit.
  4. Program commit to 0xA5A5A5A5 as one word, then read it back. Only after this readback does the record count as committed and the in-RAM value get published to other tasks.

CRC-16 is enough for a 16-byte payload here because the threat is a torn or partially programmed word, not an adversary. If the record also crosses a trust boundary, use CRC-32 and a MAC, and say so explicitly. A CRC will not stop a crafted record.

Recovery trace

Power loss pointWhat boot scan seesRecovered state
During erase of inactive pageActive page intact, inactive page erased or partially erasedLast committed record from active page
During payload programRecord with bad CRC or commit == ERASED_WORDPrevious record, torn record skipped
During commit word programCommit word is 0xFFFFFFFF, a partial value, or 0xA5A5A5A5Accepted only if exactly 0xA5A5A5A5 and CRC passes, otherwise previous record
After commit readback, before RAM publishValid committed record on flashThat record, replayed at boot
During erase of a page after compactionOther page holds the compacted snapshot plus newer recordsSnapshot plus newer records

Compaction is the part candidates miss. When the active page fills, copy the live snapshot as one committed record into the other page, verify it, and only then erase the old page. Erasing the page that holds the newest committed record before its replacement is verified is the classic way to turn a recoverable power cut into data loss.

No Yes Boot Scan A and B CRC valid and commit present? Skip record Keep highest seq Replay highest seq

Failure modes I would name in the interview

A brownout that lets the CPU run while flash voltage sags can program a word to an intermediate value that reads back correctly at low voltage and fails later. I would gate writes on the brownout detector and a supply supervisor, and treat any write started below the flash minimum as uncommitted regardless of readback.

Sequence wrap and page generation: a 32-bit seq wraps after 4 billion records, which at 100 writes per second is over a year, but a page erase resets the scan. I store a page generation counter in the first record of each page and never compare sequences across generations without it.

Wear: NOR endurance is typically 10k to 100k erase cycles. Ping-ponging two pages at 100 writes per second with 64 records per page gives an erase every 0.64 s, which kills the part in days. The arithmetic forces a larger journal, write coalescing in RAM, or a different medium, and I would show that calculation before claiming the design works.

Detection in the field: boot logs the recovered sequence, the count of skipped torn records and the page generation. A rising torn-record count is an early sign of a failing supply or worn flash, long before a committed record is lost.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-64A 10 ms control task takes 3 ms and a 50 ms telemetry task takes 25 ms, yet telemetry misses its 30 ms deadline at 80 percent utilization. How do you explain that with response-time analysis?

The 90-second answer

Utilization tells you whether the processor has enough capacity on average. It does not tell you whether a particular task finishes before its deadline. For fixed-priority preemptive scheduling I compute the worst-case response time for the task that missed, using the execution times of every higher-priority task that can preempt it inside that window. If that computed response time exceeds the deadline, the schedule is not schedulable as configured, even at 80 percent utilization. If the computed response time fits but hardware still misses, my execution time figures are wrong and I measure them again.

Assume a Cortex-M4 running FreeRTOS, preemptive fixed-priority scheduling, and no blocking from a shared mutex in this example. The two checks are:

U = sum(Ci / Ti)          // necessary, not sufficient
R = C + sum(ceil(R / Tj) * Cj)   // j = higher priority tasks

C is worst-case execution time, T is period, and R is iterated until it stops growing or passes the deadline D.

Worked trace for the stated numbers

TaskPeriod TWCET CDeadline DC/T
control10 ms3 ms10 ms0.30
telemetry50 ms25 ms30 ms0.50

U = 0.30 + 0.50 = 0.80. The processor has spare capacity, so a utilization check alone says the set is fine.

Response time for telemetry, which is the lower-priority task:

IterationCalculationR
12525 ms
225 + ceil(25/10) * 334 ms
325 + ceil(34/10) * 337 ms
425 + ceil(37/10) * 337 ms

R settles at 37 ms, which exceeds the 30 ms deadline. Control itself is fine: its response time is just its own 3 ms. The miss happens because control runs three or four times inside the telemetry window, and each preemption adds 3 ms. A 50 ms period does not protect a 30 ms deadline. That distinction is the whole point of the analysis.

Checking the inputs on hardware

RTA is only as good as C. I measure worst-case execution time with the DWT cycle counter and confirm it on a scope with a GPIO toggle, using worst-case inputs such as a full sensor frame and flash wait states enabled. Interrupt time also belongs in the budget. A UART ISR that runs for 8 us at 200 Hz consumes 1.6 ms per second, and that cost has to appear somewhere in the interfering tasks.

C
/* Cortex-M4, DWT cycle counter at 168 MHz */
static inline uint32_t cycles_now(void) { return DWT->CYCCNT; }

uint32_t start = cycles_now();
telemetry_step();
uint32_t elapsed_us = (cycles_now() - start) / 168; /* 168 cycles per us */
if (elapsed_us > 25000) { log_wcet_violation(elapsed_us); }

If the measured worst case is larger than the 25 ms used above, I rerun the iteration with the real figure. I also check for a blocking term B, the longest time a lower-priority task can hold a mutex that telemetry needs. Adding B to the first iteration is the standard way to include it, and an unbounded B from a mutex held across a blocking I2C transfer will defeat any priority assignment.

What to change

The options follow directly from the equation. Shorten telemetry execution time by splitting the work or moving a transfer to DMA. Lengthen the deadline if the application allows it, since 37 ms fits inside a 50 ms period. Raise telemetry above control only if its deadline genuinely matters more, and then rerun the analysis for control, because control may now miss. I would not respond by lowering the measured C in the spreadsheet. After any change I rerun the iteration and log the worst observed response time per task during a soak test at maximum bus load.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-65When would you assign task priorities by rate monotonic instead of deadline monotonic, and how would you check the set is schedulable?

The 90-second answer

Use rate monotonic (RM) when every task has deadline equal to its period. Use deadline monotonic (DM) when deadlines differ from periods but none exceeds its period. RM orders by period, shortest first. DM orders by relative deadline, earliest first. For independent periodic tasks with D = T, the two orderings coincide, so RM is the simpler default. When D < T for some tasks, RM can miss a deadline that DM would meet.

RM is optimal among fixed-priority schemes under the Liu and Layland assumptions: independent, preemptive, periodic tasks, D = T, no blocking. Its sufficient utilisation test is U <= n(2^(1/n) - 1), which tends to 69% as n grows. That bound is sufficient, not necessary. A set above 69% can still be schedulable, so you confirm with exact response time analysis (RTA) rather than rejecting it on utilisation alone.

DM is optimal among fixed-priority schemes when D <= T for all tasks, the result by Leung and Whitehead. It needs the deadlines to be real requirements, not copies of the periods. If you invent deadlines, DM just encodes the invention.

DM is not optimal once some D > T. A task with slack can be given too much priority by deadline order, and a single-job RTA is no longer enough because several jobs of the same task can be pending in one busy period. For D > T, use Audsley's optimal priority assignment, which searches priority orderings and tests each with RTA over the full busy period, or consider EDF if deadlines are dynamic and the scheduler supports it.

Worked example

Hypothetical but realistic figures for a Cortex-M4 at 168 MHz, times in ms:

TaskPeriod TDeadline DWorst-case C
control10103
sensor2084
logger505010

Utilisation U = 3/10 + 4/20 + 10/50 = 0.70. RM orders control, sensor, logger. DM orders sensor (D=8), control (D=10), logger (D=50). The sensor jumps ahead of control under DM because it must finish 8 ms after release, even though it runs half as often.

RTA iterates R = C + sum(ceil(R / T_j) * C_j) over higher-priority tasks, plus a blocking term B if a lower-priority task can hold a mutex or disable interrupts. With B = 0 here:

OrderTaskRTA traceRMeets D?
DMsensor44yes, 8
DMcontrol3 + ceil(R/20)*47yes, 10
DMlogger10 + ceil(R/10)*3 + ceil(R/20)*420yes, 50
RMcontrol33yes, 10
RMsensor4 + ceil(R/10)*37yes, 8
RMloggersame as above20yes, 50

Both pass in this case, but the margin differs. Under RM the sensor finishes at 7 ms against an 8 ms deadline, so 1 ms of extra sensor execution or a 1 ms blocking term from an ISR would miss it. Under DM it finishes at 4 ms. If sensor C rose to 6 ms, RM would give R = 6 + 3 = 9 ms and miss, while DM would give R = 6 ms and still pass. That is the practical failure mode of RM with D < T.

Python
import math

def response_time(task, higher):
    r = task["C"]
    while True:
        new = task["C"] + sum(math.ceil(r / h["T"]) * h["C"] for h in higher)
        if new == r:
            return r
        r = new
        if r > task["D"]:
            return r  # already missed, stop early

Feed it tasks sorted by the chosen ordering. If any R exceeds D, the assignment fails regardless of the utilisation bound. For D > T, extend this to check each job in the busy period, not just the first.

Choosing in practice

SituationChoiceReason
---------
All D = T, periodic, independentRMOptimal, no deadline data needed
Some D < T, such as a sensor that must land before a control stepDMOptimal for D <= T, RM can starve the tight-deadline task
Some D > T, such as logging with slackAudsley OPA or EDFDM is not optimal here, and RTA must cover multiple jobs
Aperiodic or sporadic tasks, offsets, shared resourcesNeither aloneUse DM or OPA with RTA including blocking, or EDF if deadlines are dynamic

Two caveats interviewers probe. First, both schemes assume preemptive fixed priorities on one core. On a dual-core part or with DMA and ISRs competing, the analysis must include interrupt blocking and core affinity. Second, priority assignment does not fix priority inversion. If the logger holds a bus mutex while the sensor waits, add B to the sensor RTA and use priority inheritance or ceiling on that mutex, or the computed R is fiction.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-66How do you detect and handle a periodic RTOS task that overruns its period?

The 90-second answer

In FreeRTOS I keep the expected wake time in a variable and call xTaskDelayUntil(&xLastWake, xPeriod). If the job finishes before the next period, that call sleeps until the deadline. If the job is still running at the deadline, the call returns immediately, with no sleep, and the next period starts late. That return value is the overrun signal. I count it, log it once with the tick count, and then decide whether to skip the missed cycle or run a shortened catch-up. I never let a periodic control task loop back-to-back trying to make up lost periods.

C
// FreeRTOS, checked against FreeRTOS Kernel 11.x
static void control_task(void *arg)
{
    const TickType_t xPeriod = pdMS_TO_TICKS(10); // 10 ms period
    TickType_t xLastWake = xTaskGetTickCount();
    uint32_t overruns = 0;

    for (;;) {
        do_control_work(); // must finish well inside 10 ms

        if (xTaskDelayUntil(&xLastWake, xPeriod) == pdFALSE) {
            overruns++;
            // xLastWake is already advanced by one period.
            // Next iteration runs immediately, then re-syncs.
            log_overrun(overruns, xTaskGetTickCount());
        }
    }
}

xTaskDelayUntil differs from vTaskDelay. vTaskDelay sleeps for a fixed interval from when it is called, so a 12 ms job followed by vTaskDelay(10) makes each cycle 22 ms. Relative to a 10 ms period, that is 12 ms of drift per cycle, and it accumulates. xTaskDelayUntil anchors to an absolute schedule, so the drift does not accumulate. The task either waits for the next slot or starts the next slot immediately.

Worked trace

Period 10 ms, job normally takes 3 ms. Times are ticks from task start.

CycleJob startsJob endsxTaskDelayUntil returnsNext start
10 ms3 mspdTRUE, sleeps 7 ms10 ms
210 ms13 mspdTRUE, sleeps 7 ms20 ms
320 ms32 ms (overrun)pdFALSE, no sleep32 ms, 2 ms late
432 ms35 mspdTRUE, sleeps 5 ms40 ms

Cycle 3 missed the 30 ms slot. Cycle 4 starts late but lands back on the 40 ms slot because xLastWake was advanced by the call. That is the behaviour I want for a control loop: one late sample, then re-synchronised, instead of a permanent phase shift.

Yes No Job finishes xTaskDelayUntil returns pdTRUE? Sleep until next period Increment overrun counter Log tick and count Skip missed sample or run shortened job

Handling the overrun

Detection alone does not fix anything. The handling depends on what the job produces.

For a sensor or control task, I skip the missed sample. Running the control law twice back-to-back on stale data can drive an actuator harder than one late run would. For a telemetry task, I drop the missed frame and send the newest reading on the next slot. For a task that accumulates state, such as a filter or integrator, I either clamp the elapsed time used in the calculation to one period or mark the output invalid for that cycle.

If overruns repeat, the design is wrong, not the detection. I check three things in order. First, worst-case execution time: measure with a GPIO toggle and a scope or logic analyser, and check the stack high-water mark with uxTaskGetStackHighWaterMark in case the job is faulting or looping. Second, interference: a lower-priority task holding a mutex, or a long interrupt, can stretch the job past its period even when the job itself is short. Third, the period itself: if the job needs 12 ms, a 10 ms period is not schedulable and the fix is a longer period, a higher priority, or splitting the work into a short periodic part and a deferred part.

Failure modes I watch for

A counter that increments but is never read hides a task that overruns every cycle. I expose the count in the diagnostics page and raise a fault after a threshold, for example 5 consecutive overruns, rather than logging forever. A second failure mode is a job that overruns only under load, such as when a DMA transfer or flash write stalls the bus. Bench timing at idle will miss that, so I test with all peripherals active and with interrupts at their worst-case rates. A third is tick wrap: comparing absolute tick counts with > breaks at wrap, which is why the comparison lives inside xTaskDelayUntil and uses the kernel's wrap-safe arithmetic. If I write my own check outside the kernel, I use unsigned subtraction, (now - deadline), cast to a signed type, instead of a direct comparison.

On bare metal without an RTOS, the same idea applies with a hardware timer compare register. I set the compare for the next period, and if the flag for the previous compare is still set when the job ends, the period was missed. The RTOS version is cleaner because the kernel already maintains the schedule and the wrap-safe comparison.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-67How do tickless idle and a slower RTOS tick cut power on a Cortex-M, and what timing failures do you have to guard against when you use them?

The 90-second answer

A fixed 1 kHz SysTick wakes the core 1,000 times a second even when no task is ready. Each wake costs an ISR, a scheduler check, and a chance to miss deep sleep. Tickless idle removes that wake when the ready queue is empty: the kernel finds the earliest delayed or blocked timeout, stops SysTick, programs a one-shot timer for that interval, and enters WFI or Stop. A slower tick, for example 100 Hz instead of 1 kHz, cuts the remaining periodic cost by 10x. Timing survives only if the one-shot wake is programmed before sleep, the tick count is corrected for the slept duration on wake, and no timeout shorter than the new tick period is silently rounded up.

How tickless idle works

On entry to idle, the scheduler holds the critical section, checks the delayed list, and computes nextWake = earliest expiry - now. If that is beyond the suppression threshold, typically 2 ticks, it calls the port hook to stop SysTick and load a hardware timer, often SysTick itself in one-shot mode or a general timer on a low-power clock. The core then executes WFI. Any interrupt, including that timer, wakes it. On wake the kernel adds the slept ticks to the tick count, unblocks tasks whose timeouts expired, and restarts periodic ticking.

The race to avoid is an interrupt arriving between the idle check and WFI. The critical section must cover the check, the timer programming, and the sleep entry, with the interrupt pending state rechecked after the timer is set. If a UART or GPIO interrupt fires in that window, the kernel must abort sleep and recompute, not sleep until the old one-shot time.

C
/* FreeRTOS-style suppression, Cortex-M, checked against FreeRTOS 11 port layer */
void vApplicationIdleHook(void) {
    uint32_t ticksToSleep;
    taskENTER_CRITICAL();
    ticksToSleep = xTaskGetTickCount() ? 0 : 0; /* placeholder for delayed-list head */
    ticksToSleep = xNextWakeTicks(); /* earliest delayed/blocked expiry, in ticks */
    if (ticksToSleep > configEXPECTED_IDLE_TIME_BEFORE_SLEEP) {
        vPortSuppressTicksAndSleep(ticksToSleep);
    }
    taskEXIT_CRITICAL();
}

In a real port, vPortSuppressTicksAndSleep stops SysTick, converts ticksToSleep to timer counts using the actual timer clock, sets the compare value, clears the pending flag, and only then issues WFI. Converting with the nominal 48 MHz core clock when the timer runs from a 32 kHz LSE or a divided APB clock is a common source of early or late wake.

What a slower tick costs and saves

Assume a 48 MHz Cortex-M4, SysTick ISR plus scheduler entry of 3 µs, and a device that would otherwise sit in Stop at 8 µA between ticks.

Tick rateISR dutyExtra average current at 45 mA activeDelay granularityWorst added latency for a 1 ms timeout
1 kHz0.3%135 µA1 msabout 1 ms
100 Hz0.03%13.5 µA10 msabout 10 ms
10 Hz0.003%1.35 µA100 msabout 100 ms

The saving is real but smaller than the sleep current suggests once the device already sleeps between ticks. The larger win is enabling deep sleep at all. At 1 kHz with a 1 ms tick, a Stop wake latency of 50 to 200 µs plus ISR time can consume most of the interval, so the core may never reach Stop. At 100 Hz the same wake cost is amortised over 10 ms.

The trade is quantisation. A task calling vTaskDelay(5) at 100 Hz waits 10 ms if the implementation rounds up to whole ticks, or 0 to 10 ms if it rounds to nearest. A 1 kHz control loop, a 2 ms sensor timeout, or a software UART bit-bang cannot move to 100 Hz without redesign. Those paths need a hardware timer or a higher rate timer interrupt independent of the RTOS tick.

yes no Idle task runs Delayed list empty? Enter deep sleep, no timer Compute earliest expiry Stop SysTick, load one-shot timer WFI Timer or peripheral IRQ wakes core Add slept ticks, unblock due tasks

Failure modes I check for

Tick count drift: if the kernel adds ticksToSleep instead of the measured elapsed time, a timer running 2% slow on an RC oscillator makes every sleep 2% long. Over a 10 s sleep that is 200 ms of drift for timestamps and log correlation. Use the timer's actual elapsed count, or a RTC-backed tick, and log the difference during bring-up.

Missed wakeup: a peripheral interrupt that does not clear the sleep state, or a one-shot timer left at its previous compare value, leaves the core asleep until the next periodic tick that no longer exists. I test this by sleeping with a GPIO wake configured and no delayed tasks, then with a delayed task and no GPIO wake.

Timeout starvation: a blocked task with a 5 ms timeout and a 10 ms tick may be unblocked late every cycle, which breaks a retry budget built on that timeout. The fix is to keep short timeouts on a hardware timer queue, or to keep the tick at 1 kHz for that build and accept the power cost.

Wake latency budget: Stop on many STM32 parts needs regulator and clock restart before code runs. If a safety ISR must respond in 20 µs, Stop is the wrong sleep mode regardless of tick rate. Sleep mode, which keeps the regulator on, wakes in a few microseconds but draws more current. Tickless idle does not fix a mode choice that already misses the deadline.

I would measure with a GPIO toggled on sleep entry and on wake, plus a current meter over a 60 s window with the same workload at 1 kHz, 100 Hz, and tickless idle. That shows whether the saving came from fewer interrupts, from actually reaching Stop, or from both, and whether wake jitter stayed inside the task deadlines.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-68Four subsystems finish initialisation at different times and the main task must start only when all of them are ready. How would you use a FreeRTOS event group to synchronise those completion flags?

The 90-second answer

Use one event group as a level-triggered set of flags, one bit per subsystem. Each initialisation task sets its bit when done. The main task blocks in xEventGroupWaitBits() until the mask for all required bits is present, or a timeout expires. Because the bits persist until cleared, a subsystem that finishes early does not lose its completion if the main task has not started waiting yet. That persistence is the main difference from a binary semaphore used as a one-shot signal.

On 32-bit FreeRTOS builds, EventBits_t is 24 usable bits. Bits 24 to 31 are reserved internally. That is plenty for startup flags and it sets a hard limit: more than 24 independent flags need a second group or a different primitive.

C
#include "FreeRTOS.h"
#include "task.h"
#include "event_groups.h"

#define SENSOR_READY  (1UL << 0)
#define CAN_READY     (1UL << 1)
#define FS_READY      (1UL << 2)
#define NET_READY     (1UL << 3)
#define ALL_READY     (SENSOR_READY | CAN_READY | FS_READY | NET_READY)

static EventGroupHandle_t startup;

void sensor_init_task(void *arg)
{
    (void)arg;
    sensor_hw_init();          /* may take 80 ms, may fail */
    if (sensor_calibrate() == 0) {
        xEventGroupSetBits(startup, SENSOR_READY);
    }
    vTaskDelete(NULL);         /* no bit set on failure */
}

void main_task(void *arg)
{
    (void)arg;
    EventBits_t bits = xEventGroupWaitBits(startup, ALL_READY,
                                           pdFALSE, pdTRUE,
                                           pdMS_TO_TICKS(5000));
    if (bits == ALL_READY) {
        control_loop_start();
    } else {
        log_startup_failure(bits);  /* bits shows which subsystem timed out */
        enter_safe_state();
    }
    vTaskDelete(NULL);
}

void app_start(void)
{
    startup = xEventGroupCreate();
    xTaskCreate(sensor_init_task, "sensor", 256, NULL, 3, NULL);
    xTaskCreate(can_init_task,    "can",    256, NULL, 3, NULL);
    xTaskCreate(fs_init_task,     "fs",     512, NULL, 2, NULL);
    xTaskCreate(net_init_task,    "net",    512, NULL, 2, NULL);
    xTaskCreate(main_task,        "main",   512, NULL, 4, NULL);
}

pdFALSE for clear-on-exit matters here. With pdTRUE, the first waiter to wake clears the bits it waited for. If a second task also waits on SENSOR_READY, it can miss a completion that already happened. Keep clear-on-exit off during startup, read the returned bits, and clear explicitly only after every consumer has seen them, or never clear a one-shot startup group at all.

Worked trace, with a 5 s timeout starting at t=0:

TimeEventGroup bitsMain task
0 msgroup created, tasks spawned0000blocked in WaitBits
80 mssensor sets its bit0001still blocked, mask not met
210 msCAN sets its bit0011still blocked
900 msFS sets its bit0111still blocked
4,800 msNET sets its bit1111wakes, returns 1111, starts control loop
5,000 mstimeout would have fired1111already running

If NET hung, the wait would return at 5,000 ms with 0111. That return value is the diagnosis. A counting semaphore per subsystem would tell you only that some waits timed out, unless you kept separate counters and inspected each one.

set bit 0 set bit 1 set bit 2 set bit 3 WaitBits ALL_READY all bits timeout Sensor task Event group CAN task FS task NET task Main task Start control loop Safe state

From an ISR, use xEventGroupSetBitsFromISR() and pass the returned BaseType_t to portYIELD_FROM_ISR(). Calling the task version from an ISR is a fault risk on most ports. Setting bits from an ISR is safe for a completion flag, but keep the ISR work to the set call. Do the recovery work in a task.

Failure modes I would name in the interview: a subsystem that fails and never sets its bit, so the timeout path must enter a defined safe state rather than starting the control loop with a dead sensor. A bit reused later for a different purpose, which turns a one-shot startup flag into a stale signal on a warm restart of that subsystem. And overlapping masks with clear-on-exit on, where one waiter clears a bit another waiter needed. All three are avoided by treating the group as write-once during boot, checking the exact returned mask on timeout, and documenting which task owns each bit.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-69When a single ISR needs to signal one task, how do direct task notifications differ from a queue in FreeRTOS, and when would you pick each?

The 90-second answer

For one producer waking one consumer, a direct task notification is the cheaper primitive. The value lives in the receiving task's TCB, so there is no queue object, no extra RAM, and no copy. A queue copies the item into queue storage, which buys buffering and multiple consumers at a cost you do not need for a single signal.

In FreeRTOS the producer side is xTaskNotifyGive() from task context or vTaskNotifyGiveFromISR() from an ISR. The consumer uses ulTaskNotifyTake() when it only needs a count, or xTaskNotifyWait() when it needs the 32-bit value itself. A queue equivalent is xQueueSendFromISR() and xQueueReceive().

C
/* ISR: DMA transfer complete, one consumer only */
void DMA1_Channel1_IRQHandler(void)
{
    BaseType_t woken = pdFALSE;
    vTaskNotifyGiveFromISR(sensor_task, &woken);
    portYIELD_FROM_ISR(woken);
}

/* Consumer task */
void sensor_task(void *arg)
{
    for (;;) {
        /* Block until at least one notification arrives.
           pdTRUE clears the count to 0 on exit. */
        uint32_t events = ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
        (void)events;
        process_latest_sample();
    }
}

The queue version of the same path needs a queue created with xQueueCreate(16, sizeof(uint32_t)), a send in the ISR, and a receive in the task. That queue holds 64 bytes of payload plus the queue structure, and every item is copied twice, once in and once out.

PropertyDirect notificationQueue
---------
---------
---------
---------
Extra RAMNone, uses a field already in the TCBQueue storage plus control structure
Data movedNone, value is written in placeOne copy in, one copy out
ConsumersExactly one taskAny number of tasks
BufferingNo queue of items, see belowBounded FIFO, send can block or fail when full
PayloadOne 32-bit word, or a pointer you manage yourselfFixed-size items, copied by value
Typical latencyLowest, no copy and no queue locking pathHigher, copy plus queue critical section

Where the behaviour diverges

The subtle part is what happens when the producer fires again before the consumer runs. With xTaskNotifyGive(), the notification value is incremented. ulTaskNotifyTake(pdFALSE, ...) decrements it by one per call, so a consumer that loops can drain three pending events. ulTaskNotifyTake(pdTRUE, ...) clears it to zero, so three events collapse into one wakeup. That is a deliberate choice, and it is the main failure mode I see: code written as a binary semaphore in disguise, where the consumer assumes one wakeup per event and silently drops two.

xTaskNotify() with eSetValueWithOverwrite is even more explicit about collapsing. It replaces the value, which suits "latest sample ready" signalling and suits nothing that must count every occurrence. A queue does not collapse. If the consumer is slow, items accumulate until the queue fills, then xQueueSendFromISR() returns errQUEUE_FULL and the producer has to decide whether to drop, overwrite the oldest item, or stop the source. That backpressure is sometimes exactly what you want, for example when each item is a distinct UART frame that must not be lost.

Worked trace, producer fires three times while the consumer is blocked on a lower priority task:

StepNotification countQueue depth (16 deep)Consumer sees
Producer event 111
Producer event 222
Producer event 333
Consumer runs, ulTaskNotifyTake(pdTRUE, 0)03One wakeup, count returned as 3
Consumer runs, xQueueReceive() once32First item only, two still queued

When I would not use a notification

Three cases push me back to a queue. First, more than one consumer, since a notification can only wake its target task. Second, payloads larger than 32 bits that the consumer must own, because sending a pointer through a notification leaves lifetime and ownership to you, whereas a queue copies the struct. Third, a producer that must be throttled when the consumer falls behind, since a notification never blocks the producer and a full queue at least makes the overload visible.

For a single ISR or DMA completion waking a single task with a flag or a count, I start with a notification, measure the missed-event behaviour under worst case load, and only add a queue when the trace shows events being lost that the application actually needed to count.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-70Two tasks each take two mutexes in opposite order and both hang forever. How do you detect that deadlock and fix it?

The 90-second answer

Two tasks hang forever when each holds one mutex and waits for the other. That is the classic hold-and-wait cycle. You detect it when both tasks are blocked on a mutex take that never times out, and you fix it by making every task acquire the same mutexes in the same global order. One ordering rule removes the cycle, because a circular wait can no longer form.

C
// FreeRTOS, Cortex-M. Two shared resources.
static SemaphoreHandle_t busMutex;    // I2C bus
static SemaphoreHandle_t cfgMutex;    // sensor config

// Buggy: opposite order
void taskA(void *arg) {               // sensor read
    xSemaphoreTake(busMutex, portMAX_DELAY);
    xSemaphoreTake(cfgMutex, portMAX_DELAY);  // waits for taskB
    read_sensor();
    xSemaphoreGive(cfgMutex);
    xSemaphoreGive(busMutex);
}
void taskB(void *arg) {               // config update
    xSemaphoreTake(cfgMutex, portMAX_DELAY);
    xSemaphoreTake(busMutex, portMAX_DELAY);  // waits for taskA
    update_config();
    xSemaphoreGive(busMutex);
    xSemaphoreGive(cfgMutex);
}

// Fixed: one global order, bus before cfg, everywhere
void taskB_fixed(void *arg) {
    xSemaphoreTake(busMutex, portMAX_DELAY);
    xSemaphoreTake(cfgMutex, portMAX_DELAY);
    update_config();
    xSemaphoreGive(cfgMutex);
    xSemaphoreGive(busMutex);
}

Worked trace of the deadlock

TimeTask ATask BState
t0takes busMutexA holds bus
t1takes cfgMutexB holds cfg
t2blocks on cfgMutexA waits for B
t3blocks on busMutexB waits for A
t4+still blockedstill blockedneither can progress, no timeout fires

With portMAX_DELAY there is no recovery. Priority inheritance does not help here. It boosts the holder when a higher priority task waits, but in a cycle both tasks are holders and waiters, so the boost changes nothing.

How you detect it on target

Do not ship portMAX_DELAY on a second lock during development. Take the second mutex with a short timeout, for example 100 ticks at a 1 kHz tick, and log on failure:

C
if (xSemaphoreTake(cfgMutex, pdMS_TO_TICKS(100)) != pdPASS) {
    // Record which task, which mutex, and which mutex it already holds.
    // In a debug build, halt or assert here. In production, count it
    // and drop the operation rather than hanging the control loop.
    deadlock_counter++;
    xSemaphoreGive(busMutex);  // release what you hold before retrying
    return;
}

That timeout turns a silent hang into a visible event you can catch with a GPIO toggle, ITM trace, or a fault handler. Track ownership in a small debug struct per mutex, set on take and cleared on give, so the log can name the holder. FreeRTOS trace tools and configASSERT on the timeout path give the same signal in a simulator. A watchdog will eventually reset the board, but by then you have lost the evidence of which pair deadlocked.

Fix options and when each fits

Global lock ordering is the default fix. List every mutex, assign an order, and require all code to follow it. It costs nothing at runtime and is easy to review in a pull request. It fails only when a new mutex is added and someone forgets the order, so keep the list in one header and grep for nested takes in review.

Try-lock with backoff is the fallback when ordering is hard to enforce, for example with a third-party driver that takes a lock internally. Take the first mutex, try the second with zero timeout, and if it fails release the first, wait a short randomised delay, and retry. That breaks hold-and-wait, but it can livelock if both tasks retry in step, and it wastes CPU under contention. Use it sparingly.

A single mutex or a queue that serialises access to both resources removes nesting entirely. That is often the cleanest answer on a small MCU: one busMutex protects the bus transaction and the config read that must stay consistent with it. The cost is coarser locking, so hold times grow and a low priority task can delay a high priority one for the length of the combined critical section. Keep that section short, with no blocking calls inside.

Task A holds bus Task A waits for cfg Task B holds cfg Task B waits for bus

The diagram is the cycle itself. Break any edge, by ordering, by try-lock, or by merging the locks, and the deadlock is gone.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-71Your ISR and a task share a 32-bit counter and a timestamp, and the ISR runs at 5 kHz: why can't you use a mutex in the ISR, and how do you build a critical section that still meets the deadline?

The 90-second answer

A mutex assumes the holder is a task that can be descheduled, can block, and can be resumed later. An ISR is none of those. It runs in handler mode, preempts whatever task was running, and if it tried to block on a mutex held by that preempted task, it would wait forever because the holder cannot run until the ISR returns. FreeRTOS and most RTOS ports therefore forbid xSemaphoreTake() from an ISR and provide xSemaphoreTakeFromISR() only for non-blocking signalling, not for mutual exclusion with a task.

For data shared between an ISR and a task, use a critical section: mask interrupts for the few instructions that touch the shared state, do the access, then restore the previous mask. Keep it to a handful of loads, stores and index updates. No allocation, no queue send that can block, no floating point, no call into a driver that takes a lock.

Why masking works, and what it costs

On Cortex-M, __disable_irq() sets PRIMASK and blocks every exception, including a safety ISR. That is correct for a 1 microsecond section and dangerous for a 50 microsecond one. The alternative is __set_BASEPRI(), which masks only interrupts at or below a chosen priority. A 5 kHz sensor ISR that shares a counter with a task can mask its own priority level and below, while a 1 kHz safety ISR at a higher priority still preempts.

The restore matters as much as the mask. Save PRIMASK or BASEPRI on entry and restore that saved value, never unconditionally enable interrupts. If the critical section is entered from a task that already had interrupts masked, or from a higher priority ISR, unconditional enable would open a window the caller deliberately closed.

C
/* Cortex-M4, CMSIS, checked against CMSIS 5.x */
static volatile uint32_t sample_count;
static volatile uint32_t last_sample_us;

/* Task side: read a consistent pair */
uint32_t read_snapshot(uint32_t *us_out)
{
    uint32_t primask = __get_PRIMASK();
    __disable_irq();
    uint32_t count = sample_count;
    uint32_t us = last_sample_us;
    __set_PRIMASK(primask);
    *us_out = us;
    return count;
}

/* ISR side: update both fields, never block */
void SENSOR_IRQHandler(void)
{
    uint32_t now = timer_us();
    sample_count++;
    last_sample_us = now;
    /* Clear the peripheral flag before exit, or it re-enters at once */
    SENSOR->SR = 0;
}

The ISR does not need a critical section for its own writes if it is the only writer and the task only reads. The task needs one because the ISR can fire between the two reads and return a count from sample N with a timestamp from sample N+1. On a 32-bit Cortex-M a single aligned 32-bit load is atomic, a 64-bit value or a pair of fields is not.

No Yes, between reads Task reads count ISR fires? Task reads timestamp, pair matches ISR updates both fields Task reads new timestamp, pair torn Task masks interrupts Read both fields Restore saved mask

Worked trace and timing

Assume a 168 MHz Cortex-M4, sensor ISR at 5 kHz (200 microsecond period), safety ISR at priority 0, sensor ISR at priority 2, task at thread level.

StepWithout maskingWith masking
Task reads sample_count100100
Sensor ISR fires, increments to 101, updates timestampyesblocked for 0.6 microsecond
Task reads last_sample_usnew timestampold timestamp, matches 100
ResultCount 100 paired with timestamp for 101Consistent pair

The masked window is two loads, two stores in the ISR, and the mask instructions: roughly 10 to 20 cycles, about 0.06 to 0.12 microsecond at 168 MHz. Even a pessimistic 1 microsecond window adds 1 microsecond of latency to the safety ISR if PRIMASK is used, which is 0.5 percent of the 200 microsecond sensor period and usually inside a 10 microsecond safety budget. If that budget were 0.5 microsecond, PRIMASK would fail and BASEPRI masking only priority 2 and below would be required, because the safety ISR at priority 0 would still run.

Failure modes I check for

Forgetting to restore the saved mask, which leaves interrupts off after the first call and looks like a hang. Nesting critical sections without saving the old value, which enables interrupts inside an outer section. Putting a printf, a blocking queue send, or a mutex take inside the section, which stretches the window from cycles to milliseconds and starves every lower priority interrupt. Using a mutex in the ISR to protect a buffer the task also locks, which deadlocks when the ISR preempts the holder. On multicore parts, masking local interrupts does not stop the other core, so the same pattern needs a spinlock or a hardware semaphore instead.

FreeRTOS names the same idea taskENTER_CRITICAL_FROM_ISR() and taskEXIT_CRITICAL_FROM_ISR(), which on Cortex-M map to BASEPRI save and restore. The name changes, the rule does not: short, non-blocking, restore what you saved.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-72A flag is set in an ISR and cleared by a task on a single-core Cortex-M. How do atomic operations protect it, and when would you disable interrupts instead?

The 90-second answer

On a single core the other writer is an interrupt, not a second core. The race is preemption between the load and the store of a read-modify-write. volatile does not close that gap. It forces each access to happen, but if (flag) flag = false; is still load, test, store, and the compiler may reorder surrounding accesses.

Make the test-and-clear a single atomic exchange. The ISR stores true. The task calls atomic_exchange(&flag, false) and acts only when the returned old value is true. The ISR cannot run between the load and store inside that exchange, so it cannot set the flag and then have the task overwrite it with a stale false.

C
#include <stdatomic.h>
#include <stdbool.h>

static atomic_bool rx_ready = ATOMIC_VAR_INIT(false);

void UART_IRQHandler(void)
{
    /* read UART data register and store the byte */
    atomic_store_explicit(&rx_ready, true, memory_order_release);
}

void telemetry_task(void)
{
    if (atomic_exchange_explicit(&rx_ready, false,
                                 memory_order_acq_rel)) {
        process_received_byte();
    }
}

What the compiler emits depends on the core. On Cortex-M3 and Cortex-M4 (ARMv7-M), GCC typically lowers a one-byte atomic_exchange to a LDREXB/STREXB loop, retrying if the store-exclusive fails. Confirm in the disassembly for your compiler and flags rather than assuming it. On Cortex-M0 (ARMv6-M) there is no LDREX/STREX, so libgcc implements these atomics by masking interrupts around the access. That makes atomic_is_lock_free(&rx_ready) return false on that target, and the exchange adds interrupt latency. Check that at startup if latency matters.

The race, step by step

With a plain volatile bool, the task has already decided to clear the flag when the ISR fires:

StepTaskISRflag after step
1Loads flag as true, decides to clear ittrue
2Preempted before the storeFires, stores true for a new bytetrue
3Resumes, stores falsefalse

The store in step 3 erases the event from step 2. The task processes one byte and the second is never signalled. With atomic_exchange, steps 1 and 3 are one indivisible operation. The ISR either runs before it, and the task sees true, or after it, and the flag remains true for the next pass.

A boolean still coalesces events. If the ISR fires twice before the task runs, the task sees one true and processes one byte. An atomic flag prevents the lost clear described above, it does not count events. Use a counter or a ring buffer when each event matters.

Atomic versus masking interrupts

ApproachHow it protects the flagCostWhen I pick it
atomic_exchangeLoad and store are indivisibleA few cycles on ARMv7-M, interrupt masking on ARMv6-MDefault for a single flag or counter
Save PRIMASK, disable interrupts, restoreISR cannot fire during the read-modify-writeAdds the length of the critical section to interrupt latencyState wider than one atomic word, such as a struct updated by the ISR
atomic_flag with test_and_setSame mechanism, guaranteed lock-free in C11Holds only one value, no payloadA pure one-bit handshake or lock

Masking has its own trap. __enable_irq() re-enables interrupts unconditionally, even when the caller was already running with them disabled. Save and restore the state instead:

C
uint32_t primask = __get_PRIMASK();
__disable_irq();
/* read-modify-write the flag and any paired data */
__set_PRIMASK(primask);

Keep that window to a few instructions. If it grows to a copy or a function call, you have moved the latency problem rather than solved it.

Limits

An atomic flag protects the flag, not the data behind it. If the ISR writes a timestamp and then sets the flag, the release store and acquire load stop the compiler moving the task's timestamp read above the flag test. On a single core without DMA or cache, that ordering is what you need. With DMA writing the buffer, the flag atomic does not make the buffer coherent, and cache maintenance is still required.

Atomics also do not handle nesting. If two ISRs at different priorities both set the flag, or the same ISR can preempt itself, that interaction needs separate reasoning. And if the flag is one bit inside a shared register, operate on the whole word with atomic_fetch_or or atomic_fetch_and. A byte atomic on one bit does not stop a read-modify-write on neighbouring bits from clobbering it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-73A UART driver sends a 64-byte packet from a task and a single byte from an ISR. How do you make it safe in both contexts, and why can't the ISR just take the same mutex?

The 90-second answer

A mutex works in task context because a blocked task can be descheduled and priority inheritance can apply. An ISR has no task to block, so calling xSemaphoreTake() from an ISR will fail an assertion on FreeRTOS or corrupt the scheduler on ports without that check. The driver therefore needs two paths that share the hardware safely.

The task path takes a mutex, sends the whole 64-byte packet, then releases it. The ISR path never takes that mutex and never waits. It either sends one byte through a short critical section if the hardware allows it, or it drops the byte, or it queues the byte for the task. Which choice is correct depends on whether that byte can be delayed.

C
/* FreeRTOS 11, Cortex-M4. Task path only. */
static SemaphoreHandle_t uart_mutex;

void uart_send_packet(const uint8_t *buf, size_t len)
{
    xSemaphoreTake(uart_mutex, portMAX_DELAY);
    uart_write_blocking(buf, len); /* polls TXE, may take milliseconds */
    xSemaphoreGive(uart_mutex);
}

/* ISR path. Never blocks, never takes uart_mutex. */
void uart_isr_send_byte(uint8_t byte)
{
    UBaseType_t saved = taskENTER_CRITICAL_FROM_ISR();
    if (!uart_tx_busy) {
        uart_tx_busy = 1;
        UART->DR = byte;
    } else {
        /* Bus is mid-packet. Queue it or count the drop. */
        xQueueSendFromISR(byte_queue, &byte, NULL);
    }
    taskEXIT_CRITICAL_FROM_ISR(saved);
}

The critical section here covers only the check of uart_tx_busy and the write to UART->DR. That takes a few hundred nanoseconds on a 168 MHz Cortex-M4. Masking interrupts for a full 64-byte packet would be different. At 115200 baud one byte takes about 87 microseconds, so masking for 64 bytes would block other interrupts for roughly 5.6 ms. That is the main trade-off between a critical section and a mutex.

MechanismWhere it can runWhat it protectsMain cost
MutexTask onlyWhole packet, including blocking waitsISR cannot use it, task can block
Critical section with BASEPRI maskingTask or ISRA few instructions, such as checking a flag and writing one registerDelays interrupts at or below the mask priority for that window
Queue with FromISR variantISR produces, task consumesHandoff of bytes or eventsFixed RAM, possible overflow if the ISR produces faster than the task drains

Worked trace

Assume the task starts a packet at t0 and the ISR fires at t1, halfway through the packet.

TimeContextStateOutcome
t0TaskTakes mutex, sets uart_tx_busy, writes byte 0Packet owns the UART
t1ISRSees uart_tx_busy setDoes not write UART->DR, queues its byte instead
t2TaskWrites bytes 1 to 63, clears uart_tx_busy, releases mutexPacket completes intact
t3TaskDequeues the ISR byte and sends itByte is delayed by at most one packet time

If that delay is unacceptable, the design has to change rather than the locking. Options include a second UART, DMA with a hardware FIFO so the ISR only pushes into a ring buffer, or a higher baud rate to shorten the packet time. A common bug is to make the ISR spin waiting for uart_tx_busy to clear. That turns a short ISR into a long one and can starve the very task that would clear the flag, especially if the ISR runs at a higher priority than that task.

A practical check is to count queue overflows and lock failures in a counter and expose it in a debug build. Run both callers at their worst rates and confirm the overflow counter stays at zero and the ISR duration, measured with a GPIO toggle on a logic analyzer, stays within its budget.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-74How do you combine a hardware RNG and a monotonic counter to make a nonce that cannot be replayed?

The 90-second answer

Use the counter for uniqueness and the hardware RNG for unpredictability. A nonce built as counter || random cannot repeat while the counter never repeats, and an attacker cannot guess the next value from past nonces because the random half is fresh. Neither half alone does both jobs. A counter alone is predictable, so a captured message can be forged with the next counter value. A random value alone can repeat, especially after a reset or if the RNG stalls, and then a captured message replays cleanly.

The counter must survive reboot. Increment and persist it before the nonce is used, not after transmission. If power fails after the increment, you get a gap in the sequence. That is safe. If you increment only after sending, a reset between send and increment reuses the same counter, and the random half is the only thing standing between you and replay.

C
// Checked against STM32H7 HAL RNG and internal flash, 2024
typedef struct {
    uint64_t counter;   // persisted, incremented before use
    uint32_t random;    // fresh from TRNG for this nonce
} nonce_t;

static uint64_t persisted_counter; // loaded from flash at boot, CRC checked

bool make_nonce(nonce_t *out)
{
    uint32_t r;
    if (HAL_RNG_GenerateRandomNumber(&hrng, &r) != HAL_OK) {
        return false; // seed error, clock error, or RNG not ready
    }
    uint64_t next = persisted_counter + 1;
    if (!counter_store_commit(next)) { // dual-slot flash write + CRC, see below
        return false;
    }
    persisted_counter = next;
    out->counter = next;
    out->random = r;
    return true;
}

The receiver keeps the highest counter it has accepted for that device key. It accepts a nonce only if the counter is greater than that value, then updates the stored value. For a channel that can reorder, keep a small window, for example the last 64 counters as a bitmap, and reject anything older than the window. A replayed packet carries an old counter, so it falls outside the window and is dropped before any payload is processed.

EventCounter sentRandom sentReceiver last seenResult
Normal message 110420x8f31a2c01041Accept, store 1042
Normal message 210430x11be09d41042Accept, store 1043
Replay of message 110420x8f31a2c01043Reject, counter not greater
Power loss after commit, before send1044 committed, never sent0x77aa10f11043Next send uses 1045, gap is fine
RNG stuck at same value1045, 10460x00000000, 0x000000001044Still unique, but predictable, raise fault

Why the RNG check matters. A stuck or biased TRNG does not break uniqueness here, because the counter still differs. It breaks unpredictability. Test the RNG at startup and periodically: reject a run of identical outputs, check the STM32 RNG error flags for seed and clock errors, and refuse to issue nonces if the test fails. Do not fall back to a software PRNG seeded once at boot for a security nonce. A PRNG state can be recovered from a few outputs, and after a reset it may repeat the same sequence.

Persistence without wearing out flash. Writing a 64-bit counter to flash on every message wears the page. At 100 messages per second that is 8.6 million writes per day, far beyond a typical 10,000 to 100,000 cycle endurance rating. Use two alternating slots with a sequence number and CRC, commit the new counter in the inactive slot, and only then send. If the write is torn by power loss, the CRC fails and the previous slot is still valid. For high rates, reserve a small flash sector for the counter, or use a counter in a secure element or RTC backup register with a battery, and accept that a backup register alone does not survive a battery failure. A 64-bit counter at 1,000 nonces per second wraps after about 584 million years, so wrap is not a practical concern. A 32-bit counter at the same rate wraps in 49.7 days, which is why the wider counter is worth the extra flash bytes.

Failure modes to name in the interview. Counter stored only in RAM, so reboot replays. Counter incremented after the send, so a reset in between reuses it. Receiver that checks the random half for freshness instead of the counter, which it cannot do reliably. Counter shared across two devices or two keys, so interleaved streams look like replays to each other. Keep one counter per device identity and per key, and bind the nonce to the message with a MAC or signature over counter || random || payload, otherwise an attacker can keep the valid nonce and swap the payload.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-75How do you choose a bootloader that rejects a correctly signed image built for the wrong hardware revision, and where does that check belong in the boot flow?

The 90-second answer

A signature alone proves who built an image. It does not prove which board the image was built for. A correctly signed rev B image will verify cleanly on rev C hardware and then run with the wrong pinout, wrong memory map or wrong power sequencing. The check that stops it has to bind the hardware identity into the signed data and compare it against the identity the bootloader reads from the board itself, before the image is trusted or jumped to.

I would choose the bootloader on that binding first, then on recovery. I need a bootloader whose image format lets me add a hardware field that is covered by the signature, whose root of trust I cannot rewrite from the application, and which can refuse to boot and stay in recovery without erasing the last good slot. On most Cortex-M and small SoC parts that points to the vendor ROM or MCUboot style bootloader with a custom header, rather than a generic U-Boot image or a home grown CRC only loader. U-Boot fits a Linux SoC with external flash. It is oversized and awkward on a 512 KB internal flash MCU, and its default FIT verification does not know my board revision unless I add it.

Where the check belongs

Read the hardware identity early, from something the application cannot spoof. Options in order of strength: OTP eFuse or one time programmable revision bits, a resistor strap read through a GPIO or ADC channel, or a secure element ID. A compile time define in the application is not an identity. The bootloader reads it, parses the image header, and checks the header fields before it spends time verifying a large signature. That order matters for a denial of service case. A device that verifies a 1 MB signature for 800 ms on every boot attempt, only to reject it, is easy to keep awake.

C
/* Checked against GCC 13 for Cortex-M33, C11 */
typedef struct __attribute__((packed)) {
    uint32_t magic;
    uint16_t header_len;
    uint16_t hw_id;        /* e.g. 0x0103 = product 1, rev C */
    uint16_t hw_rev_min;
    uint16_t hw_rev_max;
    uint32_t fw_version;
    uint32_t image_len;
    uint8_t  sig[64];      /* Ed25519, over header with sig zeroed + image */
} image_header_t;

int image_acceptable(const image_header_t *h, uint16_t board_hw_id,
                     uint16_t board_rev, uint32_t min_version)
{
    if (h->magic != IMAGE_MAGIC) return -1;
    if (h->hw_id != board_hw_id) return -2;              /* wrong product */
    if (board_rev < h->hw_rev_min || board_rev > h->hw_rev_max) return -3;
    if (h->fw_version < min_version) return -4;          /* anti-rollback */
    return verify_signature(h);                          /* last, most expensive */
}

The signature must cover hw_id, the revision range and the version, not just the payload. If it covers only the payload, an attacker or a build error can copy a valid payload into a header that claims rev C. I zero the signature field, hash header plus image, and verify. The bootloader then writes the new anti-rollback counter only after a successful first boot of the new slot, not on receipt of the image. Otherwise a rejected or crashing image burns the counter and blocks rollback.

Bootloader choiceHardware bindingRecovery and cost
Vendor ROM secure bootFixed format, often only key and version fieldsSmallest, immutable, but I cannot add a revision range without vendor support
MCUboot with custom headerFull control of header and signature coverageA/B slots, serial recovery, about 20 to 40 KB on Cortex-M
U-Boot with FITPossible via FIT properties and board codeStrong on SoCs, heavy for internal flash MCUs, longer boot time
Custom CRC loaderNone unless I add signingSmallest code, no root of trust, a CRC detects corruption not a wrong board build

Failure modes I test for

A rev B image on rev C hardware must leave the device in recovery, with the rev C slot intact and a log entry over UART or SWO showing hw_id mismatch: expected 0x0103 got 0x0102. It must not jump, must not erase the active slot, and must not increment the rollback counter. A second case is a header that lies about revision range to cover both revs. That is a build system problem, so the signing server, not the developer laptop, should fill hw_id and the range from the release manifest and refuse a request that spans incompatible pinouts.

No Yes No Yes Reset Read OTP or strap ID Parse header of candidate slot HW ID and rev in range? Log mismatch, stay in recovery Signature valid? Boot slot, confirm, then bump counter

The subtle case is a board revision change that only moves a strap resistor. If the bootloader reads the strap through the same GPIO that the new revision repurposes, the identity read is wrong on exactly the boards I need to distinguish. I check the strap pin against the schematic for every revision in the range before I trust it, and I prefer OTP bits when the silicon offers them.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-76How do you read a datasheet's electrical specifications to choose a pull-up resistor and check that a bus will meet its timing and drive limits?

The 90-second answer

I read three groups of numbers together, because a pull-up that satisfies one can break another. First, the driver limits: VOL, VOH, IOL, IOH, and the test conditions they were measured at. Second, the load: total bus capacitance Cb, the sum of every device pin capacitance plus PCB and cable capacitance. Third, the timing limit that Cb and the pull-up create, usually rise time tr for I2C.

For an open-drain bus such as I2C, the pull-up has a window. It must be low enough to charge Cb within tr, and high enough that the driver can still pull the line below VOL without exceeding IOL.

Python
# I2C pull-up window, standard mode 100 kHz, tr_max = 1000 ns per I2C spec
VDD, VOL, IOL = 3.3, 0.4, 3e-3
Cb, tr_max = 350e-12, 1000e-9

Rp_min = (VDD - VOL) / IOL          # driver can sink this much
Rp_max = tr_max / (0.8473 * Cb)     # RC rise from 0.2*VDD to 0.8*VDD
print(f"Rp_min={Rp_min:.0f} ohm  Rp_max={Rp_max:.0f} ohm")
# Rp_min=967 ohm  Rp_max=3371 ohm

A 2.2 kohm resistor sits in that window. Its sink current is (3.3 - 0.4) / 2200 = 1.32 mA, under the 3 mA IOL rating used in this example, and its rise time is 0.8473 * 2200 * 350e-12 = 652 ns, under the 1000 ns limit for 100 kHz standard mode. A 10 kohm part would look safe on current and fail on timing. A 470 ohm part would meet timing and, in this example, force (3.3 - 0.4) / 470 = 6.2 mA through a pin rated for 3 mA, so VOL would rise above 0.4 V and the low level would stop being recognised.

What the datasheet actually guarantees

SpecWhat to checkCommon trap
IOL / IOHCurrent at a stated VOL / VOH, at minimum VDD, over temperatureAbsolute maximum current is not an operating rating
VOL / VOHLogic levels at that currentLevels quoted at 0.1 mA say nothing about 3 mA
Pin capacitance CinPer device, often 5 to 10 pFAdding only the MCU and forgetting EEPROM, expander and connector
Internal pull-upResistance range, often 20 to 50 kohmTreating it as a 10 kohm resistor for timing or noise margin
Cb limit400 pF for I2C, plus rise and fall limitsUsing the limit as a target instead of a ceiling

Drive strength is not a single number. A GPIO may source 8 mA at VOH = VDD - 0.4 V on one pin, but the datasheet may limit total port current or total package current to a lower figure. I check the per-pin table, the total current note, and the test voltage before I trust a number. Short-circuit current in the table is for fault analysis, not for driving a load.

Internal pull-ups are for idle level and leakage, not for a bus. Their tolerance is wide, they vary with voltage and temperature, and a 50 kohm pull-up on a 400 pF bus gives a rise time near 17 microseconds. That fails I2C at 100 kHz and makes the line easy to disturb. I use an external resistor for any bus with a timing budget and keep the internal one only for a switch input where a slow edge is acceptable.

Bus capacitance in practice

I add up Cin for every device on the segment, then add the board. A rough planning figure for a PCB trace is 1 to 2 pF per centimetre depending on stackup, and a short cable can add tens of picofarads per metre. If the total approaches the 400 pF I2C ceiling, the fix is not a smaller pull-up alone. A smaller resistor raises sink current and power, and eventually hits IOL. The other options are to shorten the bus, split it with a buffer or repeater, move to a lower capacitance level shifter, or drop the clock rate, which relaxes tr.

No Yes Read VOL VOH IOL IOH at stated conditions Sum Cin plus PCB and cable to get Cb Compute Rp_min from IOL and Rp_max from tr Window exists? Reduce Cb split bus or lower clock Pick standard value check sink current and power Measure rise time and VOL on scope

I finish by measuring. A scope on the worst-case segment should show tr with margin at minimum supply and maximum temperature, and VOL below the receiver threshold with the pull-up fitted. If the numbers on paper and the trace disagree, the capacitance estimate was wrong, and that is the figure I revise first.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-77How does oscillator accuracy over temperature affect UART framing, and when would you choose an external crystal over the internal RC oscillator?

The 90-second answer

UART sends no clock. The receiver locks onto the start bit edge, then samples each following bit at times derived from its own clock. If that clock runs fast or slow relative to the transmitter, the sampling point drifts later in the frame. By the stop bit it can land in the wrong bit, and the receiver reports a framing error.

An internal RC oscillator is cheap and starts fast, but its frequency moves with temperature. A crystal moves far less. For UART the choice comes down to whether the worst case drift over your temperature range still leaves the sampling point inside the correct bit.

Assume 8N1. That is 10 bits per frame: start, 8 data, stop. The receiver resynchronises on the start edge and samples the stop bit about 9.5 bit times later. If the two clocks differ by a fraction d, the drift at that point is 9.5 * d bits. It must stay below 0.5 bit, and a practical design keeps it below about 0.25 bit to allow for noise and the peer's own error. That gives a total mismatch budget of roughly 2 to 3 percent.

Worked example

Take a peer on a crystal, so its error is negligible. Your MCU on the internal RC is within 1 percent at 25 C, so bench tests pass. At -40 C the RC has drifted by 3.5 percent. Drift at the stop bit is 9.5 * 0.035 = 0.33 bit. The sample is still in the stop bit, but close to its edge. At 5 percent drift it is 0.475 bit, and framing errors start appearing. That is why the link fails only at temperature extremes.

Replace the RC with a 16 MHz crystal specified at 20 ppm initial tolerance and 50 ppm over temperature. Total error stays under 0.01 percent. Drift at the stop bit is under 0.001 bit. Temperature no longer threatens the UART budget.

Clock sourceError at 25 CError over -40 to +85 CUART result
Internal RC1 to 2 percent3 to 5 percent, part dependentCan exceed the 2 to 3 percent budget alone
External crystal20 to 50 ppmUnder 100 ppm totalNegligible compared with the budget

Use the figures from your MCU datasheet for the exact part. Some RC oscillators are trimmed tighter and hold about 1 percent over temperature. With a short frame and a crystal locked peer, those parts can run UART reliably without a crystal. The test is still the same: add the worst case errors from both ends and compare with the budget.

When to pay for the crystal

Choose the crystal when the product must work over industrial or automotive temperature, when the peer is also on an RC oscillator so the errors can add, or when the same clock must also serve a peripheral with a tighter requirement such as USB or CAN. The cost is the crystal, two load capacitors, board area and a slower start.

Stay with the internal RC when the temperature range is narrow, the peer is crystal locked, and the datasheet drift plus the peer error stays well inside the budget. Verify it by measuring the actual baud rate with a scope at the temperature extremes, rather than trusting the room temperature calculation. A link that only fails in the cold chamber is a clock accuracy problem until proven otherwise.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-78When shutting down a SoC with multiple power rails, in what order should you disable them relative to startup?

The 90-second answer

Disable the rails in the reverse order to the order they were enabled at startup. If startup enables VIN, then core, then I/O, then DDR, shutdown disables DDR first, then I/O, then core, then VIN last. Reset and clocks come down before any rail is removed.

That reverse order is the rule in most SoC and PMIC datasheets. It keeps a powered domain from driving into a domain that has already lost power, and it keeps the input rail up until every load on it is off.

PhaseOrder
StartupVIN, core, I/O, DDR, then release reset
ShutdownAssert reset, then DDR, I/O, core, VIN
C
// Startup order is defined by the SoC datasheet.
// Shutdown walks the same array backwards.
static const uint8_t rail_en_pins[] = {
    PIN_VIN_EN,
    PIN_CORE_EN,
    PIN_IO_EN,
    PIN_DDR_EN,
};

void power_off(void)
{
    assert_reset();
    stop_clocks();
    for (int i = (int)ARRAY_SIZE(rail_en_pins) - 1; i >= 0; i--) {
        gpio_set(rail_en_pins[i], 0);
        delay_ms(rail_delay_ms[i]);
    }
}
Shutdown requested Assert reset and stop clocks Disable DDR Disable I/O Disable core Disable VIN

The delay between rails on shutdown matches the delay used on startup. A regulator that takes 2 ms to fall needs that interval before the next rail is removed, otherwise the next domain can still see a partially powered neighbour. If a rail has an active discharge pin, assert it as that rail is disabled so the rail reaches 0 V before the next power-on.

A common failure is shutting down in the same order as startup. Removing VIN first leaves the core and I/O regulators trying to run from a collapsing input. They can drop out in an undefined order, back-power through protection diodes, and leave DDR or a peripheral holding a pin high into an unpowered SoC. The symptom is often a clean shutdown on the bench and a failed warm reboot, because a rail did not fully discharge before startup ran again.

If a rail does not fall, check the enable polarity and whether the regulator is being held up by a load through an I/O pin. Do not start the next rail, or the next shutdown step, on a timer alone when a PGOOD or power-fail signal is available. Wait for the signal, time out after a value well above the normal fall time, and log which rail failed.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-79Your firmware needs a 10 ms delay between sensor conversions but must stay in Stop mode between them: how do you replace a busy-wait loop with a low-power timer wakeup?

The 90-second answer

Stop spinning on while (HAL_GetTick() - t < 10); and let a timer that keeps running in Stop mode wake the core. On STM32L4/G0 parts that is LPTIM1 clocked from LSE (32.768 kHz) or LSI, or the RTC wakeup timer. You arm it for the delay, clear its flag, enter Stop with WFI, and do the next conversion in the LPTIM interrupt. The CPU draws microamps in Stop instead of 15 to 30 mA at 48 MHz, and the delay is set by hardware, so a higher priority interrupt arriving mid-delay does not stretch it the way a software loop does.

The trap is the clock source. SysTick and TIM2 on many parts stop in Stop mode, so a delay built on them either never fires or fires late. LPTIM and RTC are specified to run in Stop. Check the reference manual for the exact part: on STM32L4, LPTIM1 can be clocked from LSE in Stop, TIM2 cannot.

Arming it correctly

Order matters. Clear the flag before sleeping, rearm before the next sleep, and clear again on entry to the ISR. If you clear after arming, the flag from the previous wakeup is still set and the core wakes immediately, which looks like a timer fault and drains the battery at full run current.

C
/* STM32L4, LPTIM1 on LSE 32768 Hz, 10 ms delay */
#define LPTIM_ARR_10MS 327  /* 32768 * 0.010 = 327.68 */

void lptim_init(void)
{
    RCC->APB1ENR1 |= RCC_APB1ENR1_LPTIM1EN;
    RCC->BDCR |= RCC_BDCR_LSEON;
    while (!(RCC->BDCR & RCC_BDCR_LSERDY)) { }

    LPTIM1->CR = 0;
    LPTIM1->CFGR = LPTIM_CFGR_CKSEL_0;      /* LSE */
    LPTIM1->IER = LPTIM_IER_ARRMIE;         /* autoreload match */
    NVIC_EnableIRQ(LPTIM1_IRQn);
    NVIC_SetPriority(LPTIM1_IRQn, 3);
}

void delay_10ms_and_sleep(void)
{
    LPTIM1->ICR = LPTIM_ICR_ARRMCF;         /* clear stale flag */
    LPTIM1->ARR = LPTIM_ARR_10MS;
    LPTIM1->CR = LPTIM_CR_ENABLE;
    __DSB();
    SCB->SCR |= SCB_SCR_SLEEPDEEP;          /* Stop, not Sleep */
    __WFI();
    /* woken by LPTIM, GPIO, UART or RTC: check which flag is set */
}

void LPTIM1_IRQHandler(void)
{
    LPTIM1->ICR = LPTIM_ICR_ARRMCF;
    LPTIM1->CR = 0;                         /* one shot */
    sensor_convert();
}

Two details in that code decide whether it works in the field. First, __DSB() before WFI ensures the SCR write is visible. Second, the ISR does not assume the wakeup was the timer. A GPIO edge or UART byte also wakes the part from Stop, and the code must branch on the flag instead of running the conversion unconditionally.

LPTIM flag GPIO or UART Arm LPTIM, clear flag Enter Stop with WFI Wakeup source? Clear flag, stop timer Handle event, rearm timer Run conversion

What it buys, in numbers

Assume a conversion every 100 ms, a 10 ms settling delay, 20 mA run current, 8 uA in Stop, and 0.3 ms of wake and conversion overhead per cycle. Hypothetical figures for a typical L4 board, labelled as such.

MethodActive time per 100 msAverage currentLife on 2000 mAh
Busy-wait 10 ms10.3 ms at 20 mA2.06 mAabout 40 days
LPTIM plus Stop0.3 ms at 20 mA plus 99.7 ms at 8 uA68 uAabout 3.4 years

The busy-wait figure is dominated by the delay itself. Removing it cuts average current by roughly 30 times in this duty cycle. At a 1 s period the ratio is larger, because the fixed wake overhead amortises.

Failure modes to name in the interview

A spurious immediate wake loop from a stale flag, as above. A timer clocked from HSI or PCLK that stops in Stop, so the delay never expires and the device appears hung until a GPIO wakes it. Timer resolution: at 32.768 kHz one tick is 30.5 us, so a 10 ms delay has up to one tick of quantisation error, plus wake latency of about 20 to 50 us out of Stop on L4 parts. That is fine for sensor settling and fatal for a 1 us bit-banged protocol, which should stay in Sleep or run mode. Finally, a race where an interrupt fires between the decision to sleep and WFI: the flag must be checked after arming, or the core sleeps through an event that already happened. The standard fix is to clear and rearm, then test the pending flag again before WFI.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-80Your I2C bus is stuck with SDA held low after a peripheral crashes mid-transfer. How do you recover it in firmware without a power cycle?

The 90-second answer

Assume SDA is low, SCL is high or can be driven high, and the bus pull-ups are intact. A peripheral that crashed mid-byte often holds SDA low because it is waiting for the remaining clocks of that byte. The fix is to stop acting as an I2C controller, bit-bang SCL as a GPIO until the peripheral finishes the byte and releases SDA, then issue a STOP and reinitialise the I2C peripheral.

C
/* STM32-style, pins are open-drain with external pull-ups */
static bool i2c_bus_recover(void)
{
    GPIO_InitTypeDef g = {0};
    g.Pin = SCL_PIN | SDA_PIN;
    g.Mode = GPIO_MODE_OUTPUT_OD;
    g.Pull = GPIO_PULLUP;
    g.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(SCL_PORT, &g);

    HAL_GPIO_WritePin(SCL_PORT, SCL_PIN, GPIO_PIN_SET); /* release SCL */
    HAL_GPIO_WritePin(SDA_PORT, SDA_PIN, GPIO_PIN_SET); /* release SDA */
    delay_us(5);

    for (int i = 0; i < 9; i++) {
        HAL_GPIO_WritePin(SCL_PORT, SCL_PIN, GPIO_PIN_RESET);
        delay_us(5);
        HAL_GPIO_WritePin(SCL_PORT, SCL_PIN, GPIO_PIN_SET);
        delay_us(5);
        if (HAL_GPIO_ReadPin(SDA_PORT, SDA_PIN) == GPIO_PIN_SET) {
            break; /* peripheral released SDA */
        }
    }
    if (HAL_GPIO_ReadPin(SDA_PORT, SDA_PIN) == GPIO_PIN_RESET) {
        return false; /* still held: power-cycle the peripheral */
    }
    /* STOP: SDA low while SCL high, then SDA high */
    HAL_GPIO_WritePin(SDA_PORT, SDA_PIN, GPIO_PIN_RESET);
    delay_us(5);
    HAL_GPIO_WritePin(SCL_PORT, SCL_PIN, GPIO_PIN_SET);
    delay_us(5);
    HAL_GPIO_WritePin(SDA_PORT, SDA_PIN, GPIO_PIN_SET);
    delay_us(5);
    return true;
}

After that, deinitialise and reinitialise the I2C peripheral, clear its error flags, and probe the bus with a zero-length read or HAL_I2C_IsDeviceReady() before resuming normal traffic. Log the recovery count. Repeated recoveries point to a marginal peripheral, a missing pull-up, or a reset line problem.

Why the pulses work

I2C is open-drain. No device drives a line high. Each device only pulls it low or releases it, and a pull-up resistor returns it high. A slave that has sent or received part of a byte and then lost its clock will keep SDA low until it sees the clocks it expects. Nine pulses cover the worst case: up to eight data bits plus the ACK bit. As soon as SDA goes high, the slave has finished the byte and let go.

StepSCLSDAMeaning
------------
Stuck bus10Slave waiting for clocks, holding SDA low
Pulse 1 to 4toggles0Slave counts clocks, still mid-byte
Pulse 511Byte complete, slave released SDA
STOP sequence10 then 1Bus returned to idle, START is legal again

When this fails

SCL held low is a different fault. That is either legitimate clock stretching, where a slow slave holds SCL low while it converts, or a crashed slave holding SCL low. Pulsing SCL cannot help if the line never goes high. Check SCL with a scope or by reading the pin after releasing it. If SCL stays low for longer than the slave's specified stretch limit, for example 25 ms for a sensor that stretches for 10 ms, treat it as stuck and power-cycle that peripheral through a load switch or reset pin. If the MCU cannot power-cycle it, a full board reset is the remaining option.

SDA still low after nine pulses means the slave is not waiting for clocks. It may be latched up, shorted to ground, or a second device is also driving the bus. Power-cycling is the next step. A bus reset pin on the peripheral, if present, is cheaper than cutting power.

Prevention matters more than recovery. Configure the I2C peripheral with a timeout on SCL low and on the BUSY flag, and route that timeout to the recovery routine instead of blocking forever in a HAL call. Keep the recovery routine out of an ISR. It takes roughly 100 microseconds at 100 kHz timing, which is fine in a task or fault handler and too long to hide inside a high-rate interrupt.

SDA high SDA still low Detect SDA low and BUSY stuck Disable I2C peripheral Reconfigure SCL and SDA as GPIO Pulse SCL up to 9 times Generate STOP Power-cycle peripheral Reinitialise I2C and probe bus

The probe at the end is not optional. A bus that looks idle can still have a slave in a bad state. A failed probe after recovery should escalate to a peripheral reset and a logged fault, not a silent retry loop.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-81When hardware I2C hangs with SDA held low, how would you bit-bang I2C on GPIO to recover the bus, and when would you switch back to hardware I2C?

The 90-second answer

A hardware I2C hang has two possible causes. The peripheral state machine can be stuck waiting for a flag, and a slave can be holding SDA low because it lost sync mid-byte. Resetting the peripheral clears the first cause only. The fallback therefore resets the hardware peripheral, switches SCL and SDA to open-drain GPIO, clocks out up to nine SCL pulses to flush the partial byte, issues a STOP, and then either retries on hardware or finishes the transaction bit-banged.

I would use the software path to clear the bus and get one reading through, then restore hardware I2C. Bit-banging at 100 kHz keeps the CPU in delay loops for the whole transfer, so it is a recovery tool, not a replacement.

HW I2C timeout, SDA low Reset HW peripheral Pins to GPIO open-drain 9 SCL clocks STOP Retry on HW or bit-bang

Recovery sequence

First, bound every hardware wait. A 25 ms timeout for a short transfer at 100 kHz is enough and stops a task blocking forever on BUSY or a transfer-complete flag. On timeout, save the status register and the pin levels, then reset the peripheral using the vendor reset sequence, clear error flags such as BERR, ARLO and AF, and reconfigure timing and address.

If SDA is still low, the slave is the problem. A slave that missed part of a byte waits for the remaining clocks. Nine clocks cover eight data bits plus the ACK bit. Drive SCL as open-drain, release SDA, toggle SCL, and sample SDA after each rising edge. Stop early once SDA reads high, because the slave has released the line.

StepActionCheck
1Toggle SCL up to 9 timesSDA goes high
---------
2Hold SCL high, pull SDA low then highSTOP condition
---------
3Release both pinsBus idle

If SDA stays low after nine clocks, do not keep clocking. Log the fault and, if the board allows it, power-cycle the device. A shorted bus or an unpowered slave will not be fixed by more clocks.

Bit-banged transfer

The fallback needs START, STOP and byte read/write with ACK handling. Derive the delay from the core clock so it survives a clock change. At 100 kHz each half period is 5 us. After driving SCL high, poll it and wait while a slave holds it low. That wait implements clock stretching, capped at about 10 ms per bit so a faulty slave cannot hang the fallback.

C
/* Open-drain GPIO, 100 kHz, 48 MHz core clock. */
static void bb_delay_half(void) { delay_us(5); }
static void bb_scl(int high) { gpio_write(SCL_PIN, high); }
static void bb_sda(int high) { gpio_write(SDA_PIN, high); }

static void bb_start(void)
{
    bb_sda(1); bb_scl(1); bb_delay_half();
    bb_sda(0); bb_delay_half();
    bb_scl(0);
}

static void bb_stop(void)
{
    bb_sda(0); bb_scl(1); bb_delay_half();
    bb_sda(1); bb_delay_half();
}

/* 0 = ACK, -1 = NACK or stretch timeout */
static int bb_write_byte(uint8_t byte)
{
    for (int i = 7; i >= 0; i--) {
        bb_sda((byte >> i) & 1);
        bb_delay_half();
        bb_scl(1);
        uint32_t t = 0;
        while (!gpio_read(SCL_PIN)) {
            if (++t > 10000) return -1;
        }
        bb_delay_half();
        bb_scl(0);
    }
    bb_sda(1); bb_scl(1); bb_delay_half();
    int ack = gpio_read(SDA_PIN);
    bb_scl(0);
    return ack ? -1 : 0;
}

Hardware versus software

AspectHardware I2CBit-banged fallback
Speed100 kHz to 1 MHzReliable at 100 kHz
CPU costInterrupt or DMA per transferBusy loop for whole transfer
Clock stretchingHandled by peripheralPolled in software
Bus recoveryCannot flush slave holding SDANine clocks plus STOP can
Multi-masterSupportedSingle master only

Restore hardware I2C after a successful fallback transaction and count how often the fallback triggers. An occasional trigger after a glitch is acceptable. Repeated triggers point to a marginal slave, wiring fault or missing reset line, and the right fix is hardware, not permanent bit-banging.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-82On a logic analyzer, what does the time between a trigger edge and a GPIO toggled as the first instruction in the ISR measure?

The 90-second answer

That interval is interrupt latency. The trigger edge is the event the interrupt responds to, such as a timer compare output. The GPIO toggle is placed as the first instruction in the ISR, so the rising edge on that pin marks when the CPU has taken the exception and started executing ISR code. The distance between the two edges on the logic analyzer is the time the hardware and core spent getting there.

Worst-case latency is the largest value of that interval over many runs, not the average. Run the trigger thousands of times, with the normal load running, and read the maximum from the analyzer statistics. A single clean capture usually shows the best case.

C
/* Cortex-M4, GPIOA pin 5 marks ISR entry */
void TIM2_IRQHandler(void)
{
    GPIOA->BSRR = GPIO_BSRR_BS5;  /* first statement: entry marker */
    TIM2->SR = 0;                 /* clear the interrupt flag */
    /* ISR work follows */
}

Channel 0 on the analyzer goes to the trigger pin. Channel 1 goes to GPIOA pin 5. Trigger the analyzer on the rising edge of channel 0. The cursor distance from that edge to the next rising edge on channel 1 is latency. The toggle and the GPIO output delay add a small constant offset, typically tens of nanoseconds. State that the figure includes the marker, or subtract a measured offset if you need an absolute number.

Worked trace

Hypothetical figures for a 1 kHz timer interrupt on a 168 MHz Cortex-M4, captured at 100 MS/s over 10,000 triggers:

MeasurementMinTypicalMax
Trigger to ISR entry marker0.42 µs0.55 µs3.10 µs

The typical value is the normal path. The maximum is the worst case. On this capture the 3.10 µs spike lines up with a critical section where interrupts were masked for about 2.6 µs. Reporting the 0.55 µs typical value as the latency would hide that delay completely.

Trigger edge on CH0 CPU takes exception ISR entry toggle on CH1 ISR work

Latency is A to C. It does not include the ISR work from C to D. If you also toggle a second pin at the end of the ISR, the time from A to that second edge is ISR response time, a different figure. Keep the two names separate in the report, because the entry marker alone only proves when the ISR started.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-83Your I2C sensor reads correctly on the bench but NACKs and corrupts data on the board at 400 kHz. How would you use a logic analyzer and protocol decoder to find whether it is firmware, wiring, or signal integrity?

The 90-second answer

I would not start with firmware. I would capture the failing board at the failing clock, with the probe at the peripheral pins, and compare it against a known-good capture. The decoder tells me what the master intended to send. The raw waveforms tell me what the wires actually did. A mismatch between those two layers separates a protocol bug from a signal integrity bug in one capture.

Setup matters more than the decoder. For 400 kHz I2C I want at least 10 samples per SCL period, so 10 MS/s or higher, and for a 10 MHz SPI clock I want 100 MS/s. I probe SCL, SDA, and CS or the address lines with short ground springs, not long flying leads. A 10 cm ground lead adds roughly 100 nH and turns a clean edge into ringing that the analyzer samples as extra transitions. I set the input threshold to the actual logic family, 0.3 x VDD for I2C, and I record VDD and GND as analog channels if the analyzer supports it. A decoder that shows perfect bytes while the analog trace shows SDA crossing threshold twice is lying by omission.

What I look for on I2C

The decoder output for a healthy read looks like this:

TimeSCLSDADecoded
0 us11START
12 uspulses7 bits + ACKAddress 0x48, write
40 uspulses8 bits + ACKRegister 0x00
55 us11Repeated START
70 uspulses7 bits + ACKAddress 0x48, read
110 uspulses8 bits + NACKData 0x3A, STOP

On the failing board I check four things in order. First, START and STOP conditions. SDA must not change while SCL is high except for START, repeated START, and STOP. If the decoder reports a framing error or an unexpected STOP mid-byte, I look at the raw edge. That pattern usually means SDA glitches from crosstalk or a marginal rise time, not a wrong register value.

Second, ACK and NACK. A NACK on the address means the slave did not pull SDA low during the ninth clock. I check whether the address byte on the wire matches the datasheet, whether the slave had power, and whether SDA was already low from a stuck bus. A NACK only on data bytes points at the register or a busy device, for example a sensor holding the bus during conversion.

Third, clock stretching. If SCL stays low after the ACK clock while SDA is stable, the slave is stretching. The decoder should show a long SCL low period, not a missing clock. I measure it. A 30 ms stretch during conversion is legal. A stretch that never releases, with SDA low, is a stuck bus or a slave that needs a reset pulse sequence.

Fourth, rise time. I2C is open drain. The pull-up charges the bus capacitance, and the rise time is approximately tr = 0.8473 x Rp x Cb. With Cb = 350 pF for a long trace plus two devices, a 10 k ohm pull-up gives tr = 0.8473 x 10000 x 350e-12 = 2.97 us. Fast mode at 400 kHz allows at most 1 us, so the analyzer will show SDA still rising when the master samples it, and the decoder will intermittently read the previous bit. Dropping to 2.2 k ohm gives 0.65 us and usually fixes it, at the cost of higher sink current. I verify the low level current stays within the 3 mA limit for fast mode devices.

No Yes Capture at peripheral pins Decoder matches intent? Check mode, address, ACK, framing Check raw edges for ringing and glitches Measure rise time and levels Change pull-up, speed, or layout Fix firmware or wiring

What changes on SPI

SPI has no ACK, so the decoder cannot tell me the slave objected. I rely on CS framing and on comparing MOSI against MISO bit by bit. If the decoder shows the right command but MISO returns all zeros or all ones, I check CPOL and CPHA against the datasheet timing diagram first. The wrong phase shifts the sampled data by one bit, which looks like a corrupted register value but is a one line firmware change. If the data is correct at 1 MHz and wrong at 10 MHz, I look at CS setup and hold time, clock duty cycle, and ringing on SCK. A slave that samples on the wrong edge will show a first bit that changes with clock speed.

Ringing is the classic SPI trap. A fast push-pull edge on a long trace with no termination reflects at the far end. The analyzer may capture two rising edges where the slave sees one, or the slave may sample during the ring. I look for overshoot beyond VDD or undershoot below GND on the analog channel, and for a second threshold crossing within a few nanoseconds of the main edge. Shortening the trace, slowing the slew rate in the driver if the MCU allows it, or adding a small series resistor of 22 to 47 ohm at the master end damps it. I do not add a pull-up to fix SPI ringing. That fixes I2C rise time, not a transmission line reflection.

Separating the three causes

If the decoder output differs between the bench and the board with identical firmware, the cause is electrical or wiring. If the decoder output is identical and wrong on both, the cause is firmware, usually mode, address, or register sequence. If the decoder output is identical and correct but the sensor value is wrong, the cause is timing inside the device, such as a conversion delay the driver does not wait for, and I check for clock stretching or a missing delay after the command.

I finish by re-running the exact failing sequence, not a generic scan. A logic analyzer that only captures a clean scan proves nothing about the bug. The capture that matters is the one where the NACK, the framing error, or the shifted SPI word appears, with the raw edges visible next to the decoded bytes.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-84How would you choose between SWD and JTAG, and pick a debug probe, for a given MCU?

The 90-second answer

Start from the target's debug port, not the probe. Check the MCU datasheet and reference manual for which ports are implemented and which are fused or disabled. That decides the interface; the probe then has to support that interface, the target voltage, and the software you use.

SWD is ARM's 2-wire serial debug port: SWDIO, SWCLK, plus nRESET and ground. JTAG is IEEE 1149.1: TCK, TMS, TDI, TDO, usually TRSTn, plus nRESET and ground. Many Cortex-M3/M4/M7 parts implement both and let you select one at reset. Many Cortex-M0/M0+ parts implement SWD only. Cortex-A and Cortex-R SoCs commonly expose JTAG, and some also expose SWD through an ARM Debug Port, so you cannot assume either from the core name alone.

If the part implements SWD and you need breakpoints, watchpoints, flash programming and memory inspection, SWD is usually the simpler choice: fewer header pins and wider support in OpenOCD, pyOCD and vendor IDEs. Choose JTAG when the part implements only JTAG, when you need IEEE 1149.1 boundary scan of a board chain, or when your probe and software use JTAG for multi-core control. ETM trace is a separate parallel trace port, not JTAG itself; if you need it, check that the SoC routes it out and the probe supports it, whichever debug port you use for control.

SWDJTAG
Minimum signalsSWDIO, SWCLK, nRESET, GNDTCK, TMS, TDI, TDO, nRESET, GND
Common onCortex-M0/M0+ (SWD only on many parts), Cortex-M3/M4/M7/M33 (often both)Cortex-A/R SoCs, DSPs, FPGA/SoC chains, Cortex-M parts that implement both
Boundary scanNoYes, via the IEEE 1149.1 chain
Header size6-pin tag or 10-pin Cortex Debug14-pin or 20-pin header
ClockProbe and target dependent; start at 1 to 4 MHz and raise only if the link is cleanProbe and chain dependent; a long chain lowers the reliable TCK
Yes No Yes No Yes No Read datasheet: which ports are implemented and enabled? SWD implemented? SWD if you need only core debug and flash JTAG implemented? JTAG, probe must support the chain No wired debug: use UART bootloader or vendor ROM mode Need boundary scan or ETM trace port? Pick probe by voltage, software and licence for the family

Worked choice. A Cortex-M4 board with a 10-pin Cortex Debug header: use SWD. You get halt, breakpoints, watchpoints and flash programming over SWDIO/SWCLK, and on many STM32 parts SWO is multiplexed on the same header for ITM trace. The same firmware moved to a Cortex-A53 SoC: read its debug chapter first. If it exposes JTAG and you need to halt cores in a defined order or scan the board chain, use JTAG with a probe that supports that SoC family. If it exposes SWD and that covers your needs, SWD is fine. The core name alone does not settle it.

Probe and software. A CMSIS-DAP probe is a generic SWD/JTAG adapter that OpenOCD and pyOCD can drive. A vendor probe may add family-specific flash algorithms, trace support or licences. What matters in practice: the probe's I/O voltage must match the target (a 3.3 V probe on a 1.8 V target is a hardware risk), its software must know the target's flash and debug registers, and for JTAG the chain order in the software must match the datasheet order from TDO to TDI. If the order is wrong, the probe reads an unexpected IDCODE and will not connect, even with correct wiring.

INI
# openocd.cfg, STM32F4 over SWD
source [find interface/cmsis-dap.cfg]
transport select swd
source [find target/stm32f4x.cfg]
adapter speed 4000

Failure modes to check before blaming the probe. A target that boots into a bad state or holds SWDIO may not respond at a high clock: drop to 1 MHz and use connect under reset, holding nRESET low while the probe attaches. A JTAG chain containing a device that does not implement JTAG breaks the chain for devices beyond it. And a probe that supports the interface but whose software has no flash algorithm for your exact part will halt the core yet fail to program it. In each case the fix is in clock, reset, chain order or target support, not in buying a different cable.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-85Your Cortex-M4 firmware has crashed and halted in a HardFault. Walk me through how you would use OpenOCD and GDB over SWD to inspect the core without losing the crash state?

The 90-second answer

Attach without resetting, halt the core, then read the fault state before you touch anything else. A reset, a load, or even a normal GDB connect that issues a reset will erase the registers and stack you need. With OpenOCD acting as the GDB server on port 3333, I connect with target extended-remote, halt, and capture registers, fault registers, and the stacked exception frame first. Only after that do I run a backtrace or inspect memory.

Assume a Cortex-M4 running from flash, an ST-LINK or CMSIS-DAP probe, and an ELF with symbols. If the part is in a lockup state or the fault handler has already overwritten the stack, the evidence will be partial. I say that up front and check whether the core is still halted in the handler.

Setup

TCL
# openocd.cfg for an STM32F4 on ST-LINK, SWD at 1 MHz
source [find interface/stlink.cfg]
source [find target/stm32f4x.cfg]
adapter speed 1000
# Keep the target from resetting on connect during a crash dump.
# Do not add reset_config lines that force a reset here.
gdb_port 3333
telnet_port 4444

Start it in one terminal:

Shell
openocd -f openocd.cfg

In GDB, in a second terminal:

GDB
gdb firmware.elf
(gdb) target extended-remote localhost:3333
(gdb) monitor halt
(gdb) info registers
(gdb) monitor mdw 0xE000ED28 4
(gdb) x/8xw $sp
(gdb) bt full

monitor halt matters. monitor reset halt is for a fresh debug session. On a crashed target it discards the PC, LR, and stacked frame. I also avoid load at this stage. Loading rewrites flash and can fault again.

Reading the crash

On Cortex-M, hardware entry to a fault handler pushes R0, R1, R2, R3, R12, LR, PC, and xPSR onto the active stack, MSP in thread mode or PSP if the RTOS uses it. The stacked PC is the instruction after the faulting one, or the faulting instruction for a precise bus fault. The stacked LR encodes the exception number in its low bits, for example 0xFFFFFFF9 for HardFault.

The four words read from 0xE000ED28 are CFSR, HFSR, DFSR, and AFSR. CFSR splits into MemManage, BusFault, and UsageFault status. BFAR at 0xE000ED38 and MMFAR at 0xE000ED34 hold the faulting address only when the matching VALID bit is set.

Hypothetical dump, labelled as an example:

ItemValueReading
$pc0x080012a4Inside HardFault_Handler
Stacked PC at ($sp+24)0x08001f3cFaulting instruction in sensor_read()
Stacked LR at ($sp+20)0xFFFFFFF9Exception 3, HardFault
CFSR0x00008200BFARVALID set, precise data bus error
BFAR0x20001ff8Two bytes past the end of RAM
$sp0x20001f80Handler stack, frame starts here

From there I disassemble around the stacked PC, print the source line, and check the pointer arithmetic in that function. info registers alone misleads if you read the handler's PC as the crash site.

Connect without reset Halt core Save registers and fault regs Read stacked frame at SP Disassemble stacked PC Inspect memory and backtrace Dump memory for offline analysis

RTOS and memory checks

If FreeRTOS is running, info threads and the OpenOCD FreeRTOS support can show which task was active, but only if the kernel data structures are intact. I check the current task pointer and the task stack separately from the handler stack. A crash in an ISR will show MSP, not the interrupted task's PSP, so I note which stack I am reading.

For a dump I use:

GDB
(gdb) dump binary memory crash_ram.bin 0x20000000 0x20020000
(gdb) dump binary memory crash_flash.bin 0x08000000 0x08100000
(gdb) info registers > crash_regs.txt

That preserves the state if the board loses power or someone resets it.

Failure modes I check for

SymptomLikely causeFix
GDB connect resets the targetOpenOCD reset config or target extended-remote with reset on connectRemove forced reset, use monitor halt after connect
monitor halt times outSWD clock too high, bad wiring, core in lockupDrop adapter speed to 100 kHz, check VTref and GND, try monitor reset halt only after recording that state is lost
Stack looks like zerosFault handler used a different stack or stack overflow corrupted itCheck MSP and PSP, look for a canary or MPU guard hit, inspect the task stack bounds
BFARVALID clearFault was a UsageFault or an imprecise bus errorDecode CFSR and HFSR instead of trusting BFAR

If the core is in lockup, where the fault handler itself faults, OpenOCD may still halt it but the stacked frame points into the handler. I treat that as a second fault and look for what the first fault handler touched, often a shared peripheral register or a corrupted stack pointer.

The deliverable from the session is a short note with the stacked PC, fault registers, faulting address, and the source line. That is enough to reproduce the crash under a breakpoint at the stacked PC on the next run, rather than guessing from the handler address.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-86When debugging code running from cached flash, when would you use a hardware breakpoint instead of a software breakpoint, and what breaks if you patch the flash?

The 90-second answer

Use a hardware breakpoint whenever the core has one free. On Cortex-M it is a comparator in the Flash Patch Block (FPB) that watches the instruction address and halts the core when it matches. It changes no code, writes no flash, and leaves the instruction cache exactly as it was. A software breakpoint is different. The debugger overwrites the target instruction with a trap opcode, BKPT on Cortex-M or INT3 on x86, and restores it on resume. That overwrite is a flash program operation, and on cached, execute-in-place flash that is where the trouble starts.

Patching flash from a running core is slow and often impossible. Most internal flash needs a page or sector erase before programming, the erase stalls reads from that bank for milliseconds, and you cannot safely erase the bank you are executing from. The debugger therefore has to halt the core, move execution to RAM or another bank, erase, program the patched word, then invalidate the instruction cache so the core fetches the trap instead of the cached original. If cache maintenance is missed, the breakpoint silently never fires. If the code is in ROM, OTP, or locked flash, it cannot be patched at all. A hardware breakpoint has none of those failure modes, which is why it is the default for cached flash and the only option for ROM.

Software breakpointHardware breakpoint
MechanismReplaces opcode with BKPT / INT3Address comparator in FPB
Flash writeYes, erase plus programNo
Works in ROM/OTPNoYes
Works in RAMYesYes, if comparator free
LimitOne per patchable locationImplementation defined, check FP_CTRL NUM_COMP
Timing effectCache invalidate and flash stall on set and clearNegligible, code unchanged
Cache riskStale I-cache can hide the patchNone

What the hardware version looks like

On Cortex-M4 the FPB is enabled through the debug registers. A debugger such as OpenOCD or Segger J-Link does this for you, but the registers show the mechanism. FP_COMP0 holds the address to match, with bit 0 as its ENABLE bit, and FP_CTRL enables the block.

C
/* Cortex-M4, checked against ARMv7-M Architecture Reference Manual */
#define FP_CTRL    (*(volatile uint32_t *)0xE0002000u)
#define FP_COMP0   (*(volatile uint32_t *)0xE0002008u)

void hw_breakpoint(uint32_t addr)
{
    FP_COMP0 = (addr & ~3u) | 1u;        /* address in bits 31:2, bit 0 ENABLE */
    FP_CTRL  = (1u << 1) | (1u << 0);    /* ENABLE and KEY */
}

The core compares the program counter against that value on every fetch. No instruction is altered, so prefetch and the I-cache keep working normally and the halt happens at the exact instruction. The number of comparators is not fixed by the architecture. Read FP_CTRL bits 7:4, NUM_COMP, on the specific part to know how many you have, and do not assume a count from another Cortex-M variant.

When software breakpoints still win

Hardware comparators are scarce. A handful of FPB slots disappear quickly when you set breakpoints across several tasks. A software breakpoint also gives you a breakpoint at any address, including inside a large function you did not plan to debug. For code in RAM, where patching is a simple store and there is no erase, the cost is trivial. The rule I use is hardware first for flash and ROM, software only when comparators run out or the target is RAM.

Yes No, RAM Yes No Debugger sets breakpoint Code in flash or ROM? Use FPB hardware comparator Free hardware slot? Patch with BKPT No flash write, no cache flush Erase and program, invalidate I-cache

Failure modes to name in the interview

A software breakpoint set while the core runs from the same flash bank can corrupt execution if the erase completes before the debugger moves the program counter. A missed I-cache invalidate after patching produces the classic symptom where the breakpoint is listed but never hit, and the program runs the original instruction from cache. Clearing a software breakpoint also writes flash again, so repeatedly toggling breakpoints in a loop wears the flash and adds milliseconds of stall each time. Hardware breakpoints avoid all three, at the cost of a hard limit on how many you can have at once. If you need more than the FPB provides, you either reuse slots as you move through the code or accept a software breakpoint in RAM only.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-87How do you draw the line between what firmware must handle and what the schematic must guarantee for a peripheral interface?

The 90-second answer

Hardware owns the electrical state of a pin when firmware is dead, unpowered, or still in reset. Firmware owns everything that depends on time, sequence, and recovery after that state is established. If a behaviour must hold during a crash, a brown-out, or the 40 ms before main() runs, it belongs on the schematic. If it depends on a clock edge, a timeout, or a retry, it belongs in firmware. Most field failures I have seen sit exactly on that boundary because neither side wrote the contract down.

ConcernSchematic owns itFirmware owns it
Pin level at resetPull-up or pull-down, default enable stateNothing. It cannot assume a floating pin.
Voltage and current limitsLevels, series resistors, protection, decouplingStaying inside them, detecting overrange
Power sequencingRail order, reset supervisor, back-powering pathsWaiting for power-good, sequencing enables in code
Bus timingPull-up value, trace capacitance, terminationClock rate, timeouts, clock stretching handling
Recovery from a stuck peripheralTest points, reset line wired to a GPIOIssuing the reset, toggling clocks, re-init
Calibration and thresholdsReference components, divider accuracyTrim, filtering, hysteresis in software

A worked boundary: I2C pull-ups and a sensor reset

Take a 3.3 V I2C bus at 400 kHz with 180 pF of total bus capacitance. The rise time limit is 300 ns. Firmware cannot fix a pull-up that is too weak, and hardware cannot fix a bus clocked too fast for the pull-up that is fitted. The shared calculation is:

Rp(max) = tr / (0.8473 * Cbus) = 300e-9 / (0.8473 * 180e-12) = 1967 ohm
Rp(min) = (Vdd - Vol) / Iol = (3.3 - 0.4) / 0.003 = 967 ohm

A 1.5 kΩ pull-up sits inside that window. A 10 kΩ pull-up, common on slow buses, gives a rise time of about 1.5 µs and the first bit sampled at 400 kHz is still low. No driver tweak recovers that. Conversely, a 470 Ω pull-up sinks 6.2 mA per device, which exceeds the 3 mA sink rating on many sensors. The schematic picks the resistor, firmware picks the bus speed, and both must agree on the capacitance budget before layout.

The same split applies to a reset pin. Wire the sensor reset to a GPIO with a hardware pull-down, so the sensor is held in reset while the MCU boots. Firmware then releases reset, waits the datasheet minimum of 5 ms, and only then issues the first I2C transaction. If the pull-down is missing, the sensor can come up in a random state and ACK an address before firmware has configured it. That looks like a firmware bug in the log and is a schematic omission.

C
/* Checked against STM32G4 HAL, but the sequence is portable. */
static int sensor_init(void)
{
    HAL_GPIO_WritePin(SENSOR_RST_GPIO_Port, SENSOR_RST_Pin, GPIO_PIN_RESET);
    HAL_Delay(5); /* datasheet minimum reset pulse */
    HAL_GPIO_WritePin(SENSOR_RST_GPIO_Port, SENSOR_RST_Pin, GPIO_PIN_SET);
    HAL_Delay(10); /* datasheet startup time before first transaction */
    return i2c_probe(SENSOR_ADDR); /* fails here if reset or pull-up is wrong */
}

Note what the code does not do. It does not try to recover a sensor that was never held in reset, and it does not bit-bang a bus that has no pull-up. Those are not firmware responsibilities.

No Yes No ACK ACK Power applied Power-good and reset supervisor OK? Hardware holds enables off, bus pulled to idle Firmware releases reset in datasheet order Firmware probes device and checks ID register Log, toggle reset, retry with timeout Normal operation

Where the boundary breaks in practice

Back-powering is the classic case. A sensor powered from a GPIO or from the MCU's 3.3 V rail through a diode can power the I2C bus through its protection diodes when the MCU is in Stop mode. SDA then sits at 0.6 V, below the logic high threshold, and the bus looks stuck. Firmware can add a bus recovery routine that clocks SCL nine times, but it cannot fix a rail that is being back-fed. The fix is a series resistor, a bus switch, or powering the sensor from the same rail as the MCU, decided on the schematic.

A second failure is an enable pin with no hardware default. A motor driver enable that floats during reset can turn on for a few milliseconds at every power-up. Firmware sees a current spike it did not command. The fix is a pull-down on the enable and a gate drive that defaults off, not a faster boot.

When I review a new board, I ask for three things in writing: the pin state table at reset, the power sequence diagram with rail order, and the bus budget calculation above. If those three exist, the firmware/hardware argument usually ends quickly. If they do not, the argument happens later, on a returned unit, at higher cost.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-88Tell me about a hardware-only bug that took you an afternoon to corner, and how you proved it was not firmware?

The 90-second answer

A 12-bit ADC on a motor controller read a current shunt correctly in simulation and on the bench with the motor disconnected. On the assembled board, with the motor running, it produced a 1 kHz spike of about 180 counts every 50 ms. I spent the first hour in firmware. The second hour with a scope proved the ADC input itself moved.

The board switched a 20 kHz PWM at 12 V through a MOSFET. The shunt amplifier shared a ground return with the MOSFET source. Each PWM edge pulled the amplifier reference by roughly 55 mV for 3 µs. At 3.3 V full scale, 55 mV is about 68 counts on a 12-bit converter, and the measured spike was larger because the amplifier output also rang. The firmware sampled at a fixed 1 kHz timer edge, so it sometimes landed inside that 3 µs window. Simulation had no ground bounce, so it never reproduced.

I proved it was hardware by freezing the firmware and moving only the sampling instant. When the sample moved 20 µs away from the PWM edge, the spike disappeared with no code change to the conversion path. The fix was a 10 Ω series resistor and 100 nF capacitor at the ADC input, a separate return for the amplifier, and a sampling phase that avoided the switching edge. The spike fell below 4 counts.

How I cornered it

First I ruled out the obvious firmware suspects without guessing. I logged raw ADC counts, DMA half-transfer flags, and the timer capture value in the same record. If DMA or the ISR were late, the timestamp would move. It did not. The count changed while the timestamp stayed fixed.

Then I toggled a GPIO at the start of the ADC conversion and probed three points at once: the GPIO, the shunt amplifier output, and the ADC reference pin. That gave a direct timing correlation instead of a theory.

ConditionGPIO to ADC triggerAmplifier outputADC referenceRaw count
Motor off, bench supply0 µs1.650 V steady3.300 V steady2048 ± 2
Motor on, sample on PWM edge0 µs1.650 V, 55 mV dip for 3 µs3.300 V, 18 mV dip2048, spike to 2228
Motor on, sample 20 µs after edge20 µs1.650 V, settled3.300 V, settled2048 ± 3
Motor on, after RC filter and layout change0 µs1.650 V, 6 mV dip3.300 V, 2 mV dip2048 ± 4

The middle row is the evidence. Same firmware, same motor current, only the phase changed. A firmware averaging bug cannot depend on the phase relative to a PWM edge in that way.

C
/* Cortex-M4, timer triggers ADC. GPIO marks the trigger for the scope. */
#define ADC_PHASE_COUNTS 20  /* 20 timer counts after PWM edge, 1 MHz timer */

void pwm_edge_isr(void)
{
    GPIO_TOGGLE(DEBUG_PIN);              /* scope trigger */
    TIM_SetCompare(TIM_ADC, ADC_PHASE_COUNTS);
    TIM_ClearFlag(TIM_PWM, TIM_FLAG_CC1);
}

void adc_done_isr(void)
{
    uint16_t raw = ADC_Read();           /* no averaging here */
    log_raw(raw, TIM_GetCounter(TIM_ADC));
    GPIO_TOGGLE(DEBUG_PIN);
}

I kept averaging out of the test build on purpose. Averaging would have hidden the spike and left the root cause in place.

Yes No Yes No Spike only on hardware Log raw count plus timestamp Timestamp moves? Check ISR and DMA timing Toggle GPIO at ADC trigger Scope amplifier and reference Shift sample phase Spike follows phase? Fix return path and filter Re-examine firmware path

What I would say if pushed

The afternoon was mostly spent resisting a firmware fix. A moving average, a median filter, or discarding the highest sample would have made the symptom smaller and the product worse, because the same bounce also reached the overcurrent comparator input. The scope trace showed the input pin moved, so the converter was reporting the truth.

Two checks now go into every mixed-signal bring-up. I sample once at the worst phase on purpose during testing, and I probe the reference pin, not just the signal pin. If the reference moves, no amount of digital filtering restores the lost accuracy. In this case 18 mV of reference movement is about 22 counts of error even with a perfect signal path, which the bench test with a clean supply never showed.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-89How would you trade off code size, RAM and power when choosing a microcontroller for a battery-powered product?

The 90-second answer

I start from the product constraints, not the datasheet headline numbers. I fix three budgets first: maximum flash the firmware plus bootloader plus any update slot can occupy, maximum RAM for stacks, buffers and RTOS objects, and an average current budget derived from battery capacity and required life. A part that misses any one budget is out, even if it wins on the other two. Only then do I compare sleep current, wake time, integrated peripherals and unit cost among the survivors.

For a concrete case, assume a sensor node on a 2000 mAh cell that must run 3 years, wake every 10 s, and support signed over-the-air updates. The average current budget is 2000 mAh / (3 x 8760 h) = 76 uA. That number drives everything else.

Worked power budget

Hypothetical but realistic figures for a Cortex-M0+ class part at 3.0 V:

StateCurrentTime per 10 s cycleCharge per cycle
Sleep (RTC on, RAM retained)4 uA9.88 s39.5 uC
Active, 16 MHz, sensor read + radio6 mA120 ms720 uC
Total10 s759.5 uC

Average current = 759.5 uC / 10 s = 76 uA. That exactly meets the budget, with no margin. If the active current were 9 mA instead of 6 mA, average rises to 112 uA and life falls to about 2.0 years. This is why I compare parts on measured active current at the clock and voltage I will actually run, plus sleep current with the peripherals I will actually keep on, not the lowest number in the table. A part with 1 uA sleep but 12 mA active can lose to a part with 4 uA sleep and 5 mA active when the duty cycle is 1 percent or higher.

Code size and RAM budgets

Flash is rarely the firmware size alone. With A/B updates I need two application slots plus a bootloader:

Bootloader:              16 KB
Application slot A:      96 KB
Application slot B:      96 KB
Total flash required:   208 KB  -> choose 256 KB part, not 128 KB

I check the real size from the build, not an estimate:

C
/* Checked with arm-none-eabi-size and the linker map after -Os */
/* .text + .rodata must fit one slot with 10-15% headroom for growth */
/* .data + .bss + stacks + heap must fit RAM with stack watermarks checked */

RAM budget for the same node, on a 32 KB RAM part:

ConsumerBytes
RTOS heap and task stacks (4 tasks)8192
Radio and sensor DMA buffers4096
TLS or crypto scratch, if used6144
Static globals and .data/.bss4096
Margin for stack growth and fragmentation4096
Total26624

That leaves about 5 KB spare. On a 16 KB part the same firmware does not fit without cutting the crypto scratch or moving buffers to flash, which changes the design. I would rather move to the next RAM size than ship with under 20 percent spare, because stack growth and a larger radio buffer are the usual late changes.

How I choose among survivors

Fix life, size and RAM budgets Reject parts that miss any budget Measure sleep and active current on eval board Check wake latency and retained RAM Check integrated peripherals vs external parts Check supply, package and unit cost at volume Pick part with margin on all three budgets

Integrated peripherals matter for power and cost together. A part with a built-in low-power comparator, RTC and ADC that can run in sleep can remove an external chip that draws 2 to 3 uA continuously. That saving is worth more than a small difference in core current. I also check wake latency: some Stop modes wake in 5 us, others need 1 to 2 ms for the regulator and clock to settle. At a 120 ms active window that difference is small, but for a 2 ms wake-and-sample design it can double the energy per cycle.

Failure modes I watch for: a datasheet sleep figure measured with all GPIOs floating or with flash powered down in a mode that loses RAM, so my retained-RAM mode draws 15 uA instead of 2 uA; a flash size that fits today but leaves no room for a second slot, forcing an unsafe in-place update; and a RAM size that fits the linker map but fails once the RTOS heap grows or an ISR stack is added. I catch those by measuring current with a power analyser over a full 10 s cycle, dumping the map file, and running with stack watermark checks for a week before committing to a part.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-90How do you review a pull request for a driver change for race conditions, buffer overflows, and error-path issues?

The 90-second answer

I read a driver diff in three passes, in order of how badly each bug hurts. First, shared state: anything touched by an ISR, DMA, or another task. Second, bounds: every length, index, and shift that comes from hardware or from a caller. Third, error paths: what the code leaves running when a step fails halfway.

For shared state I ask who else can run between two lines. A read-modify-write on a status register, a head/tail pair updated in an ISR and a task, a flag set in the ISR and cleared in the task, all race if the compiler or an interrupt lands in the gap. volatile stops the compiler caching the register, it does not stop the ISR preempting you mid-update. The fix is a short critical section, a single-producer single-consumer ring with indices updated in the right order, or a hardware atomic like the STM32 BSRR write. I also check the reverse direction: does the ISR read a buffer the task is still filling, and does DMA still own that buffer when the task frees it?

For bounds I trace every length back to its source. A length from a datasheet register, a read() return, or a user ioctl is untrusted until checked. The classic failure is a uint16_t length multiplied or shifted into a size_t copy, or a signed int count compared against an unsigned size. I look for the check that caps the copy at the destination size, and for the check that rejects a zero or oversized transfer before the peripheral starts.

For error paths I walk the failure branch line by line. If the probe fails after the clock is enabled, after DMA is armed, or after the interrupt is unmasked, does the cleanup disable the clock, stop DMA, and mask the interrupt again? A driver that returns -ENODEV with DMA still running will corrupt the next buffer that reuses that memory. I also check that every return value is handled, that a partial transfer reports how many bytes actually moved, and that a failed write() does not leave the device half configured.

What I look for in the diff

PassConcrete checkBug it catches
Shared stateISR/task shared variable guarded, or single writerTorn 32-bit read, lost flag, ring overwrite
Shared stateRegister write is atomic or inside critical sectionRMW race clears a status bit set by hardware
BoundsCopy length capped at destination, checked before startStack or heap overflow from a long hardware read
BoundsInteger type of length matches the copy APISign or width truncation on a large transfer
Error pathClock, DMA, IRQ cleaned up on every early returnDMA writing into freed memory after probe fails
Error pathPartial transfer count returned, not just an error codeCaller retries a full buffer and duplicates data

A diff I would send back

C
/* Before: races and leaks on the error path */
int uart_read(struct uart *u, uint8_t *dst, uint16_t len)
{
    u->dma_len = len;              /* ISR can fire here */
    dma_start(u->rx, len);         /* no cap against sizeof(u->rx) */
    if (wait_ready(u) != 0)
        return -ETIMEDOUT;         /* DMA and IRQ left running */
    memcpy(dst, u->rx, len);       /* len from caller, unchecked */
    return len;
}
C
/* After: bounded, and cleanup runs on every failure */
int uart_read(struct uart *u, uint8_t *dst, size_t len)
{
    if (len > sizeof(u->rx))
        return -EINVAL;
    irq_disable(u->irq);
    u->dma_len = (uint16_t)len;
    dma_start(u->rx, (uint16_t)len);
    irq_enable(u->irq);
    if (wait_ready(u) != 0) {
        irq_disable(u->irq);
        dma_stop();
        return -ETIMEDOUT;
    }
    memcpy(dst, u->rx, len);
    return (int)len;
}

The second version still needs a check I would ask about in review: who owns u->rx while DMA runs, and can a second call start before the first finishes? If two tasks can call it, the function needs a mutex or a busy flag, not just the IRQ guard. That question, plus the cleanup on the timeout path, is usually where the real bug hides.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-91Your 1 kHz control task measures 210 µs worst in testing, but you must guarantee it never misses its 500 µs deadline: how do you estimate its true WCET from measurements and static bounds?

The 90-second answer

A measured maximum is a lower bound on worst-case execution time, never the bound itself. Testing shows what happened on the inputs, cache state, interrupt load and bus contention you happened to create. A guarantee needs a bound built from the code paths that testing may miss, then checked against measurements.

For a control task I combine three things: instrumented measurements over a stressed input space, a static bound on each loop and call, and interference from interrupts and shared hardware. If the summed bound fits the deadline with margin, I trust it. If measurements exceed the bound, the bound is wrong and I find the missing path before shipping.

Worked bound

Assume a 168 MHz Cortex-M4, 1 kHz control period, 500 µs deadline. The task does a fixed PID calculation, a calibration lookup and a CAN transmit request. Hypothetical figures, labelled as such:

ComponentMeasured maxStatic bound used
PID and filters, fixed loops96 µs110 µs
Calibration search, 96 entries18 µs typical, 41 µs seen85 µs, binary search plus interpolation on every branch
Error and saturation handling0 µs in normal runs35 µs, rarely taken branch
CAN queue and driver22 µs40 µs, queue full case
Interrupt interference in window28 µs55 µs, two higher priority ISRs
Blocking on bus or DMA0 µs seen20 µs, one lower priority critical section
Total210 µs observed345 µs bound

Response time check: R = C + sum ceil(R / Tj) * Cj + B. With C = 270 µs for the task itself, B = 20 µs, and one 200 Hz ISR costing 25 µs, R converges near 345 µs. That leaves 155 µs margin to the 500 µs deadline. The gap between 210 µs and 345 µs is the point. The unobserved paths account for most of it.

Measurement that can be defended

C
/* Cortex-M4, DWT cycle counter, checked against a GPIO toggle on a scope */
static inline uint32_t now_cycles(void) {
    return DWT->CYCCNT;
}

uint32_t t0 = now_cycles();
control_step();
uint32_t dt = now_cycles() - t0;   /* unsigned wrap is safe for dt < 2^32 */
if (dt > wcet_observed) wcet_observed = dt;
GPIO_TOGGLE; /* scope confirms DWT scaling and ISR entry overhead */

I log a histogram, not just a maximum, and I force the conditions that create the maximum: cold cache and branch predictor after a flash erase, lowest supply voltage, highest temperature the product allows, calibration inputs at table boundaries, sensor faults, queue full, and DMA running at full rate. I also run the task with interrupts artificially delayed to see the blocking term. A GPIO toggle matters because DWT counts cycles, not wall time lost to a stalled bus or a flash wait state that the core counts differently on some parts.

Where static bounds come from

For each loop I need an iteration bound I can state in a review. A binary search over 96 entries has at most 7 iterations. A filter loop over a fixed sample count is exact. A while loop waiting for a peripheral flag has no bound from the code alone, so I replace it with a timeout and bound the timeout, or I move the wait out of the control task. Compiler output at -O2 changes instruction counts, so I bound the compiled binary, not the C source, and I recheck after any optimisation change. Tools such as AbsInt or Bound-T do this analysis, but a hand count with the disassembly open catches the paths tools model conservatively.

No Yes Instrument task with DWT and GPIO Stress inputs, cache, voltage, DMA, faults Record histogram and observed max Bound loops, calls and rare branches Add ISR interference and blocking Bound fits deadline with margin? Remove unbounded wait or shrink work Re-measure bound against hardware

Failure modes I check for

Cold start after reset often runs 30 to 80 µs slower than warm steady state because flash prefetch and cache are empty. A calibration table in flash with wait states costs more when DMA is stealing bandwidth. A CAN or I2C driver that retries on error can multiply its cost, so the bound must include one retry or the retry must be deferred to a lower priority task. Priority inversion adds blocking that never appears in a single task measurement. Finally, a measurement taken at -O0 tells you nothing about the -O2 binary that ships, and vice versa.

The deliverable is a number I can defend in a design review: observed maximum, static bound, interference term, and margin, each tied to a test or a code path. If any term is a guess, I say so and shrink the task until it is not.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-92On a Cortex-M4 with 256 KB RAM and 512 KB flash that must start within 100 ms, how would you test RAM, flash and a critical I2C sensor at boot and decide what to do on failure?

The 90-second answer

I would split boot into a fast path that must pass before anything safety related runs, and a slower path that can run while non-critical subsystems start. The fast path checks the things that make later code untrustworthy: RAM the stack and heap will use, the flash image the CPU is about to execute, and the clock and watchdog that everything else depends on. If any of those fail, I do not continue into the application. I record the failing test ID in a retained register or no-init RAM, trigger a controlled reset or halt in a safe state, and let the bootloader or external watchdog decide the next attempt.

Peripherals come next, but only the ones the application cannot start without. A UART used for diagnostics, the I2C bus used for a sensor, and a GPIO output that drives an enable pin are worth testing at boot. A display or a second serial port can be tested lazily on first use. That keeps boot time bounded and avoids turning a cosmetic fault into a bricked device.

fail pass fail pass critical fail degraded fail pass Reset, clocks, watchdog early RAM test Record ID, safe halt Flash CRC and signature check Critical peripheral checks Mark subsystem absent, continue Start RTOS and application

RAM: test before you trust it

The cheap tests catch the faults that matter in production: a stuck data bit, a stuck address line, and coupling between neighbouring cells. A full March test is thorough but slow. On a 256 KB RAM part at 100 MHz, a March C- style sequence does roughly 10 passes over every word. That is 2.6 million word accesses, about 26 ms if each access takes one cycle, and more like 80 to 120 ms once loads, stores and loop overhead are counted. That is acceptable for a safety critical boot, too slow if the product must be ready in 100 ms.

I use a tiered approach. At every boot I run a fast pattern over the RAM that will hold the stack, heap and DMA buffers: write 0x00000000, 0xFFFFFFFF, 0xAAAAAAAA, 0x55555555 and a walking 1, then read back and compare. That catches stuck bits and many address faults in a few milliseconds. A longer March test runs in the factory, after a firmware update, or periodically in idle time. I never test the exact stack region while the stack pointer points into it. The test either runs from a small known-good region in ROM or from a reserved scratch area, and it restores the stack pointer afterwards.

C
/* Checked against C11, Cortex-M4, no cache on the test region. */
static int ram_pattern_test(volatile uint32_t *start, volatile uint32_t *end)
{
    static const uint32_t patterns[] = {
        0x00000000u, 0xFFFFFFFFu, 0xAAAAAAAAu, 0x55555555u,
        0x12345678u, 0x87654321u
    };
    for (unsigned p = 0; p < sizeof(patterns) / sizeof(patterns[0]); p++) {
        for (volatile uint32_t *w = start; w < end; w++) {
            *w = patterns[p];
        }
        for (volatile uint32_t *w = start; w < end; w++) {
            if (*w != patterns[p]) {
                return (int)(w - start);
            }
        }
    }
    return -1;
}

Returning the offset matters. A failure at offset 0x1F40 on every boot points at a specific solder joint or a damaged RAM cell. A failure that moves around points at power, clock or a marginal cell. I log the offset and the pattern that failed.

Flash: verify what you are about to execute

I do not rewrite flash at boot to test it, because a power cut during that write could corrupt the image I am trying to protect. Instead I compute a CRC-32 over the application image and compare it with a value stored in a header that the bootloader already verified, or with a digest stored in OTP or in a separate metadata sector. If the image is signed, the signature check in the bootloader is the stronger test and the CRC is a fast pre-check that catches bit rot and a torn update.

For a 512 KB image, reading flash through a hardware CRC unit at roughly 100 MB/s takes about 5 ms. A software CRC-32 at 20 MB/s takes about 25 ms. Either is fine at boot. I also check the vector table: initial stack pointer inside RAM, reset handler inside the expected flash range, and no erased 0xFFFFFFFF entries. That catches a partially written image that still has a valid CRC over the wrong length.

A spare sector, if the part has one, can get a real write and erase test in the factory. At boot I only read it back and check its CRC. Testing erase cycles in the field wears the part for no benefit.

Peripherals: test the contract, not the whole datasheet

TestMethodDetectsOn failure
Clock treeRead PLL lock and divider status, measure a timer output on a GPIOWrong crystal, failed PLL, wrong dividerHalt, clocks are fundamental
WatchdogStart it early, pet it only after RAM and flash passCode that hangs before mainLet it reset, record cause
UART loopbackSend a known byte string, compare received bytesWrong baud, broken TX or RX pin, clock errorDegraded if diagnostics only, halt if it is the control channel
I2C probeAddress scan of expected devices, check ACK and bus idleSDA or SCL stuck low, wrong pull-ups, missing deviceDegraded, mark device absent
ADC referenceSample the internal bandgap or a fixed dividerReference drift, wrong VREF selectionDegraded or halt depending on use
GPIO enableToggle an output, read back input if looped, check a status pinShorted pin, missing enable supplyHalt if it gates power

Each test gets a timeout. An I2C probe that waits forever for a clock edge turns a missing sensor into a hung boot. I bound every wait with a timer tick and treat a timeout as a failure, not as a reason to retry indefinitely. Retries are limited to two or three attempts for a bus that can glitch, then the subsystem is marked absent.

Failure policy and boot budget

I keep a small table of test IDs, the last result for each, and a boot counter in no-init RAM. On a failure I write the ID and the detail word, such as the RAM offset or the I2C address that did not ACK, then reset. If the same test fails three boots in a row, the device stays in the safe halt state instead of looping forever and draining a battery. A field technician can read the ID over SWD or a diagnostic UART and know whether to replace the board, check the sensor connector, or reflash.

The budget I aim for on a typical Cortex-M4 product is under 50 ms for the fast path: about 10 ms for RAM patterns over the critical region, 5 to 25 ms for the flash CRC, and a few milliseconds for clock, watchdog and bus probes. The full March test and a full peripheral sweep run in the background after the RTOS starts, and their results are reported on the next boot if they fail. That gives a device that starts quickly, refuses to run on untrustworthy memory or code, and still tells you exactly which part failed.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-93How would you version a sensor calibration record in flash and use a CRC to decide at boot whether to use it, migrate it, or reject it?

The 90-second answer

Store each calibration record with a schema version and a CRC-32 computed over the version, length, and payload. At boot, check the magic and length first, then the CRC. If the CRC fails, reject the record and use factory defaults. If the CRC passes and the version matches the firmware, use it directly. If the CRC passes and the version is older, migrate the fields in RAM to the current format. If the version is newer than the firmware understands, reject it rather than guessing at unknown fields.

The CRC answers "is this record intact?" The version answers "do I know what these bytes mean?" You need both, because an intact record from a newer firmware can still be unreadable to older code.

Record layout

Keep the on-flash format fixed and explicit. Do not store a C struct directly, since padding and field order are compiler defined. Serialize fields in a defined order, little-endian, and place the CRC last so it covers everything before it.

FieldSizePurpose
magic4 BRejects erased flash, which reads as 0xFF
schema_version2 BPayload format, for migration
payload_len2 BBounds the payload and the CRC
payloadvariableOffset, gain, temperature coefficient
crc324 BCRC-32/IEEE over all preceding bytes

CRC-32 uses polynomial 0xEDB88320 and detects all single-bit errors and burst errors up to 32 bits. A random corruption passes with probability about 1 - 2^-32. CRC-16 would pass about 1 in 65,536 corrupt records, which is a weak bet for data that shifts every measurement the sensor makes. Cover the version and length in the CRC. If only the payload were covered, a corrupted length could make the reader copy bytes that were never written as calibration.

C
/* C11, checked against a CRC-32/IEEE implementation. */
#define CAL_MAGIC 0x43414C31u /* "CAL1" */

typedef struct __attribute__((packed)) {
    uint32_t magic;
    uint16_t schema_version;
    uint16_t payload_len;
    uint8_t  payload[44];
    uint32_t crc32; /* over all preceding bytes */
} cal_record_t;

bool cal_crc_ok(const cal_record_t *r) {
    if (r->magic != CAL_MAGIC) return false;
    if (r->payload_len > sizeof(r->payload)) return false;
    uint32_t crc = crc32_ieee((const uint8_t *)r,
                              offsetof(cal_record_t, crc32));
    return crc == r->crc32;
}

Boot decision

Run the checks in order, cheapest and most structural first. A bad magic or an out-of-range length means the bytes are not a record at all, so there is no point computing a CRC over them.

Stored stateCRCAction
erased flash (0xFF)n/aReject, use factory defaults
magic or length invalidn/aReject, use factory defaults
valid headermismatchReject, use factory defaults, count the failure
version 2, firmware expects 2matchUse payload as stored
version 1, firmware expects 2matchMigrate in RAM, use migrated values
version 3, firmware expects 2matchReject, use factory defaults

Migration is a small pure function. Suppose version 1 stored one offset per sensor. Version 2 adds a gain and a temperature coefficient. The migrator copies the offset, sets gain to unity in fixed point, and sets the coefficient to zero. Those defaults preserve the old behaviour while the new fields wait for a real recalibration. The migrated record is used in RAM only. Rewriting flash at boot is unnecessary work and adds a write at the moment the device is least tested.

The newer-version case matters after a firmware rollback. Older code cannot know whether version 3 reordered the payload or changed its units, so applying it would produce plausible but wrong readings. Rejecting it and running on factory defaults, with a diagnostic counter set, makes the mismatch visible instead of silent.

no yes no yes yes older newer Read record from flash Magic and length valid? Use factory defaults CRC matches? Version equals current? Use payload Migrate fields in RAM Start sensor

One detail candidates often miss: validate the record you just wrote, not just the one you read at boot. After programming a new calibration, read it back and run the same CRC check before treating the write as done. That catches a failed program operation while the old values are still available, instead of discovering a bad record on the next power cycle.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-94How would you implement a UART command parser that handles partial frames and malformed bytes without executing a bad command?

The 90-second answer

Never parse a UART stream as if one read equals one command. Bytes arrive split across interrupts, garbage appears after a reset, and a host can send half a frame then stop. I keep a byte-at-a-time state machine that persists between calls, validates length and CRC before dispatching, and resynchronises on the next sync byte when anything fails.

Assume a fixed frame I control on both ends: AA 55 LEN CMD PAYLOAD[LEN] CRC16_LO CRC16_H, where CRC16-Modbus covers LEN through the payload, and LEN is capped at 64. The parser has four states: SYNC1, SYNC2, HEADER, BODY. It only acts on a complete, CRC-valid frame. Everything else is counted and discarded.

C
// Checked against C11, Cortex-M4, no dynamic allocation.
#include <stdint.h>
#define MAX_PAYLOAD 64
typedef enum { S_SYNC1, S_SYNC2, S_HEADER, S_BODY } state_t;
typedef struct {
    state_t st;
    uint8_t len, idx;
    uint8_t cmd;
    uint8_t payload[MAX_PAYLOAD];
    uint8_t crc_lo, crc_hi;
    uint16_t crc;
    uint32_t last_byte_ms;
} parser_t;

static uint16_t crc16_update(uint16_t crc, uint8_t byte) {
    crc ^= byte;
    for (int i = 0; i < 8; i++)
        crc = (crc & 1) ? (uint16_t)((crc >> 1) ^ 0xA001) : (uint16_t)(crc >> 1);
    return crc;
}

// Returns 1 when a valid frame is ready in p, else 0.
int parser_feed(parser_t *p, uint8_t byte, uint32_t now_ms) {
    if (p->st != S_SYNC1 && (now_ms - p->last_byte_ms) > 100)
        p->st = S_SYNC1;  // sender stalled mid-frame: drop it
    p->last_byte_ms = now_ms;
    switch (p->st) {
    case S_SYNC1:
        if (byte == 0xAA) p->st = S_SYNC2;
        break;
    case S_SYNC2:
        if (byte == 0x55) { p->st = S_HEADER; p->crc = 0xFFFF; }
        else if (byte != 0xAA) p->st = S_SYNC1;
        break;
    case S_HEADER:
        if (byte > MAX_PAYLOAD) { p->st = S_SYNC1; return 0; }
        p->len = byte; p->idx = 0; p->crc = crc16_update(p->crc, byte);
        p->st = S_BODY;
        break;
    case S_BODY: {
        // idx 0 = CMD, 1..len = payload, len+1 = CRC_LO, len+2 = CRC_H
        if (p->idx == 0) {
            p->cmd = byte;
            p->crc = crc16_update(p->crc, byte);
        } else if (p->idx <= p->len) {
            p->payload[p->idx - 1] = byte;
            p->crc = crc16_update(p->crc, byte);
        } else if (p->idx == (uint8_t)(p->len + 1)) {
            p->crc_lo = byte;
        } else {
            p->crc_hi = byte;
        }
        p->idx++;
        if (p->idx == (uint8_t)(p->len + 3)) {
            uint16_t got = (uint16_t)(p->crc_lo | ((uint16_t)p->crc_hi << 8));
            p->st = S_SYNC1;
            return (got == p->crc) ? 1 : 0;
        }
        break; }
    }
    return 0;
}

The ISR or DMA callback pushes bytes into a ring buffer. The task drains the ring and calls parser_feed per byte. That split matters: the ISR stays short, and a partial frame simply leaves the parser in S_BODY until the rest arrives or the 100 ms gap timeout fires. CRC bytes live in crc_lo and crc_hi, separate from payload, so a maximum length frame writes payload[0] to payload[63] and never past the end.

SYNC1 yes no yes no yes no byte from ring state byte == AA? SYNC2 byte == 55? HEADER: check LEN BODY: collect CMD + payload CRC ok? dispatch cmd

Worked trace. Host sends AA 55 03 10 01 02 03 CRC_LO CRC_H for command 0x10 with 3 payload bytes, but the link drops the last two bytes, then a later valid frame arrives.

Bytes fedParser state afterEffect
AA 55 03 10 01S_BODY, idx=2Waiting, no dispatch
(100 ms gap, next byte arrives)reset to S_SYNC1Partial frame dropped, counter incremented
AA 55 02 20 09 08 CRC_LO CRC_HS_SYNC1 after CRC checkCommand 0x20 dispatched once
AA 55 FF ...S_SYNC1 at headerLEN=255 exceeds cap, frame rejected immediately
AA 55 02 20 09 08 BAD_CRCS_SYNC1 after CRC checkNo dispatch, resync on next AA

Failure modes I name in the interview. A length byte corrupted to a large value would make the parser swallow the next real frame as payload, so the cap check in S_HEADER rejects it before any buffer write. A corrupted sync byte just keeps the parser in S_SYNC1, which costs nothing. A bad CRC discards the frame but the following AA 55 starts cleanly, so one noisy burst does not poison the stream. Unknown commands get a NAK with the command byte echoed, rather than silence, so the host can tell a dead link from a rejected command. I also count crc_fail, len_fail, and timeout in a diagnostics struct. A rising timeout count at 115200 baud usually means the host is sending at the wrong baud or the sender clock drifted, which ties back to oscillator tolerance, not parser logic.

When not to use this: if the host is a terminal sending human-typed lines, a line-based parser ending on \n is simpler and easier to debug with a terminal emulator. The binary state machine pays off when payload bytes can contain any value, including AA, 55, and \n, and when a torn frame must never be executed.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-95Your protocol needs CRC-16 over 256-byte frames at 1 kHz on a Cortex-M4 with a hardware CRC unit: how do you decide between hardware and software CRC, and what would you measure to justify it?

The 90-second answer

First check whether the hardware unit can express the protocol at all. A CRC is not just a width. Polynomial, initial value, reflected input and output, and final XOR all have to match. On STM32F4 the CRC peripheral implements CRC-32 IEEE only, with a fixed polynomial. It cannot do CRC-16/CCITT-FALSE or CRC-16/MODBUS without workarounds. On STM32G0, H7 and newer parts the polynomial and reversal are programmable, so the same question has a different answer. If the parameters do not match, software is the only correct option, regardless of speed.

If the parameters do match, decide on measured cost at your frame size and rate, not on the assumption that hardware is always faster.

Assume a Cortex-M4 at 168 MHz, 256-byte frames at 1 kHz, so 256 kB/s of CRC work. A table-driven software CRC-16 processing one byte per iteration at roughly 4 cycles per byte costs 256 x 4 = 1024 cycles, about 6.1 us per frame, or 0.61% of CPU at 1 kHz. A bitwise implementation at roughly 40 cycles per byte costs about 61 us, or 6.1%. A hardware unit fed in 32-bit words needs 64 writes plus setup and readback, typically under 1 us of CPU if the data is already in RAM, and it can be fed by DMA with no per-word CPU cost on parts where the CRC data register is a DMA destination. Those figures are illustrative, so measure them on your build with the DWT cycle counter and a GPIO toggle around the call, at -O2, with the table in flash and the buffer in its real location.

FactorSoftware table CRCHardware CRC unit
---------
Polynomial and reflectionAny variant, change the table or codeOnly variants the unit supports
CPU costScales with bytes, predictable per byteScales with words, plus fixed setup per frame
Short frames, 16 to 32 bytesSetup is a few instructions, often winsRegister writes and reset can dominate
Long frames, 1 kB and upTable lookups and flash reads add upDMA feed keeps CPU free, wins clearly
DeterminismNo peripheral state to resetMust reset or seed correctly between frames
PowerCPU stays active longerPeripheral and DMA can run while CPU sleeps, if the low-power mode allows it
C
/* Reflected CRC-16/MODBUS, table driven, checked at -O2 on Cortex-M4 */
static uint16_t crc16_modbus(const uint8_t *buf, size_t len)
{
    uint16_t crc = 0xFFFFu;
    for (size_t i = 0; i < len; i++) {
        crc = (uint16_t)((crc >> 8) ^ table[(crc ^ buf[i]) & 0xFFu]);
    }
    return crc;
}

For the hardware path, feed the same buffer through the data register in 32-bit chunks when length and alignment allow it, otherwise fall back to byte writes, then read the result register once. Confirm the unit's input reversal setting matches the protocol, because a reversed input with a non-reversed polynomial gives a plausible-looking but wrong CRC that the receiver will reject on every frame.

No Yes Short or infrequent Long or frequent Protocol CRC parameters Polynomial, init, reflect and xorout match hardware? Software table CRC Frame length and rate? Hardware CRC, DMA fed if available Measure worst case with DWT CYCCNT

Three failure modes decide this in practice. First, a silent parameter mismatch. The transmitter and receiver both compute a CRC, both look correct in isolation, and every frame fails. Test against published check values, for example CRC-16/MODBUS of the ASCII string "123456789" is 0x4B37, before testing over the wire. Second, stale state between frames. If the hardware register is not reset or reseeded, the CRC of frame two includes frame one, which passes bench tests with single frames and fails in a stream. Third, reading the result before the feed finishes. With DMA, the CPU must wait for the DMA complete flag, not just for the last write to the data register, and the buffer must be in RAM the DMA can reach, with the alignment the peripheral requires for word writes. Reading early returns the CRC of a prefix of the frame, which changes with timing and looks intermittent.

My default on a modern part with programmable CRC is hardware for frames above roughly 128 bytes or above a few hundred frames per second, software below that, and software whenever the polynomial is fixed to CRC-32 and the protocol wants CRC-16. Revisit the choice if the frame format changes, because a unit that fits today may not fit the next protocol revision, while the table version changes in one place.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-96You log one 32-byte event per second to 16 x 4 KB sectors of internal NOR flash rated at 10,000 erase cycles. How would you lay out the log so wear spreads evenly, and how long will the flash last?

The 90-second answer

Use a circular log. Append fixed-size records one after another in the current sector. When that sector is full, erase the oldest sector and start writing there. Each sector is erased once per full wrap of the pool, so erase cycles spread evenly across all 16 sectors without any separate wear-leveling logic.

NOR flash explains why the layout has to look like this. Programming can only clear bits from 1 to 0, so a written byte cannot be changed back without erasing its whole sector. Erasing a 4 KB sector on a typical STM32F4 class part takes roughly 100 ms to 700 ms, and endurance is about 10,000 cycles. In-place updates are therefore impossible, and erasing on the write path would stall the firmware.

Record layout and crash safety

Fixed-size records make recovery a linear scan. Write the record body first and a commit byte last. A power cut during the write leaves the commit byte at its erased value of 0xFF, so the partial record is ignored on the next boot. A CRC catches a record where the commit byte landed but earlier bytes did not.

C
// C99, checked on a little-endian Cortex-M4. Hypothetical layout.
#define RECORD_SIZE 32u
#define COMMIT_OK   0xA5u

typedef struct {
    uint32_t seq;         // monotonic across reboots
    uint32_t tick_ms;
    uint16_t event_id;
    uint16_t crc16;       // CRC-16/CCITT over seq through payload
    uint8_t  payload[12];
    uint8_t  commit;      // programmed last, 0xFF until committed
    uint8_t  pad[3];
} __attribute__((packed)) log_record_t;

The writer programs the struct with commit still 0xFF, then programs commit = COMMIT_OK as a separate final write. The reader accepts a record only when the commit byte matches and the CRC checks out. Sequence numbers order records after a wrap and reveal a missing record.

Lifetime for the stated numbers

With 16 sectors of 4 KB, 32-byte records, one event per second, and a 10,000-cycle rating:

QuantityCalculationResult
Records per sector4096 / 32128
Records per full wrap16 x 1282,048
Time per wrap at 1 Hz2,048 records / 1 per sabout 34 min
Erases per sector per day86,400 / 2,048about 42
Expected lifetime10,000 / 42about 238 days

That last row decides whether the design is acceptable. At 10 events per second the same pool lasts about 24 days, and no rotation scheme fixes that. The fixes are a larger pool, buffering events in RAM and flushing less often, or moving the log to FRAM or external SPI flash with higher endurance.

Erase timing

yes no Append event Room left in current sector? Program record, commit byte last Erase oldest sector in idle task Verify sector reads back as 0xFF Advance write pointer

Erase the next sector during idle time, before it is needed. If the current sector fills before that erase finishes, hold new events in a small RAM buffer sized for the worst-case erase time. At 1 Hz and a 700 ms erase, four slots cover the gap with margin. If the buffer still overflows, drop the oldest buffered event and increment a dropped counter so the loss is visible in diagnostics.

Verify the sector after erasing. A sector that does not read back as 0xFF, or that fails verification twice, should be retired from the pool and the wrap shortened by one sector. Retrying it forever would silently lose every record written there.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-97Walk me through how you would design a battery sensor node that wakes on schedule, samples, transmits, and returns to deep sleep without drifting or missing cycles?

The 90-second answer

Use the RTC as the only scheduler. The MCU spends almost all its life in Stop 2 or Standby, wakes on an RTC alarm, runs a fixed sequence with a hard time budget, transmits, then re-arms the next alarm from the scheduled time rather than from now. That one choice stops drift accumulating when a cycle runs long.

Assume a node sampling every 60 s, a sensor that needs 30 ms to convert, and a sub-GHz or BLE radio that needs 80 ms to transmit. Hypothetical figures below are for sizing, replace them with datasheet values for your parts.

PhaseDurationCurrentCharge per cycle
Wake, clocks, sensor power-on15 ms12 mA0.18 mC
Sensor conversion and ADC35 ms8 mA0.28 mC
Radio TX, one attempt80 ms35 mA2.80 mC
Housekeeping, flash log, sleep entry20 ms10 mA0.20 mC
Sleep in Stop 2, RTC running59.85 s2.5 uA0.15 mC

Total active charge is about 3.46 mC per 60 s cycle. Average current is 3.46 mC / 60 s plus sleep, roughly 60 uA. On a 2000 mAh cell that is 2000 mAh / 0.060 mA, about 33,000 hours or 3.8 years before self-discharge and temperature derating, which in practice dominate. The radio is 80 percent of the active charge, so cutting retries or shortening the payload buys more life than any MCU optimisation.

RTC alarm fires Wake, restore clocks Power sensor, start conversion Sample ADC, check range Transmit, bounded retries Log result, re-arm next alarm Enter Stop 2

The firmware shape is a single wake handler, not a free-running RTOS loop. On a bare-metal STM32L4 or similar part that keeps the sleep state explicit:

C
// C11, STM32L4 HAL style, called from the RTC wakeup interrupt
void rtc_wakeup_handler(void)
{
    uint32_t now = rtc_now_seconds();
    uint32_t next = next_slot;              // scheduled, not now + 60
    if ((int32_t)(now - next) > 5) {
        next = now + 60;                    // missed slot, resync once
    }
    sensor_power_on();
    start_conversion();
    wait_for_conversion(50);                // ms timeout, not a busy loop
    sample = read_adc();
    sensor_power_off();
    tx_send(frame, 2);                      // at most 2 attempts
    log_to_flash(sample);                   // append only, CRC per record
    rtc_set_alarm(next);
    enter_stop2();                          // clocks off, RAM retained
}

Three details decide whether this works in the field.

1. Alarm arithmetic. Re-arming from now adds the whole active time to every period. A 150 ms active phase on a 60 s period is a 0.25 percent rate error, which is 3.6 minutes a day, and it grows if retries stretch the cycle. Arming from the next scheduled slot keeps the long-term rate set by the RTC alone. Use unsigned subtraction for the missed-slot check so the comparison survives a 32-bit tick wrap. If the node is already more than half a period late, skip the missed slot and resync, rather than firing back-to-back transmissions and draining the battery.

2. Power gating and leakage. Power the sensor from a load switch or a GPIO-driven regulator, and put every unused pin in analog mode before sleeping. A single pin left as a digital input with a 10 kOhm external pull can add 300 uA, which is 100 times the Stop 2 budget and would cut the life estimate above from years to months. Measure sleep current with the sensor physically disconnected first, then reconnect it. If the two numbers differ, the sensor's shutdown current or the regulator's quiescent current is the problem, not the MCU.

3. Bounded work. Give each phase a timeout and a failure path that still sleeps. A sensor that never signals conversion complete must not hold the node awake. A radio that gets no ACK must stop after the retry budget and log the loss, not retry until the battery is flat. Record a sequence number and the RTC timestamp in every frame so the receiver can tell a dropped cycle from a dead node.

Failure modes I would check on the bench: RTC drift over temperature, since an internal LSI can be off by several percent and an external 32.768 kHz crystal is needed if the schedule matters to better than a minute a day; wake latency after Standby, where the full reset and clock restore can add 20 ms that Stop 2 avoids; and brown-out during the radio pulse, where a weak cell sags below the reset threshold mid-transmission and the node boot-loops. A bulk capacitor sized for the TX pulse and a brown-out reset level above the radio's minimum voltage prevent the last one. Log the actual wake-to-sleep duration in flash for the first hundred cycles. If it exceeds the budget in the table, the average current calculation is wrong regardless of what the datasheet sleep figure says.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-98A device fails intermittently in the field but passes bench tests. What is the first step before you start changing firmware?

The 90-second answer

Reproduce it before you change any code. A bench pass only proves the device works at bench conditions. Field failures usually need a condition the bench never applies, such as heat, low supply voltage, full load or long uptime. If you cannot make it fail on demand, every fix is a guess and you cannot tell whether the guess worked.

The rule is simple: no reproduction, no fix. Add logging to capture the failure, then stress the device until the same failure appears on the bench. Once it reproduces, the cause usually becomes visible in minutes. Without that step, teams often rewrite a driver, add a delay, or patch a race that was never the cause, then ship the same failure again.

ConditionBench testField unitHow to apply it on the bench
TemperatureRoom temperatureCold start, hot enclosureSoak in a chamber at the specified extremes while running
Supply voltageClean lab supplyBattery sag under loadUse a programmable supply and step the load while logging VDD
RuntimeMinutesWeeks of uptimeRun continuously and force tick values near wrap
LoadIdle or light trafficFull interrupts, DMA and radio trafficRun the worst case workload and measure timing jitter

Test the extremes together. A fault that needs heat plus load plus a low battery will not appear if you test each variable alone.

Capture the failure first

Field units need to report what happened. Store a small record in no-init RAM so it survives a reset, and copy it to flash only when a fault occurs. That avoids wearing flash on every boot.

C
// C11, Cortex-M4. g_fault survives reset because it is in .noinit.
typedef struct {
    uint32_t magic;
    uint32_t tick_ms;
    uint32_t fault_code;
    uint16_t vdd_mv;
    uint16_t temp_c_x10;
    uint32_t crc;
} fault_record_t;

__attribute__((section(".noinit"))) fault_record_t g_fault;

void fault_snapshot(uint32_t code, uint16_t vdd_mv, uint16_t temp_c_x10)
{
    g_fault.magic = 0xF17A11C5u;
    g_fault.tick_ms = tick_now();
    g_fault.fault_code = code;
    g_fault.vdd_mv = vdd_mv;
    g_fault.temp_c_x10 = temp_c_x10;
    g_fault.crc = crc32((uint8_t *)&g_fault, sizeof(g_fault) - 4u);
}

At boot, check the magic value and CRC. If both pass, report the record through the diagnostic interface and clear it. Add counters for reset reason, watchdog resets and brown-out resets. A counter turns a vague report into a rate you can compare after a fix.

Yes No Field failure reported Read fault snapshot and counters Stress bench at field conditions Same failure reproduced? Fix cause and retest at extremes Ship logging build and collect more data

What to do with the result

When the bench reproduces the failure, disable subsystems one at a time. If the failure stops with the radio off, look at supply droop and interrupt load before you touch sensor code. If it stops at low temperature, look at oscillator accuracy and timing margins. That single bisect usually points at the right subsystem.

If the bench still does not reproduce it, do not rank fixes by which code looks weakest. Ship the logging build, collect snapshots from more units, and wait for a pattern. Hypothetical example: 8 of 10 field failures show low VDD and a brown-out counter increment. That pattern ranks the supply path ahead of a rare watchdog reset, even if the watchdog fix looks easier. The snapshot decides the order, not preference.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-99How would you document a driver API so another engineer can use it correctly without reading the register manual?

The 90-second answer

Document the contract, hide the registers. Another engineer should be able to write correct calling code from the header and one example, without opening the datasheet. That means every public function states its preconditions, its units and ranges, what it blocks on, which context it may run in, who owns the buffers, and what each error code means in terms of what to do next. Register names, clock trees and interrupt flags stay in the .c file and in a separate hardware notes section for the maintainer.

I would ship three things together: a header that is the API, a short usage example that compiles, and a table of errors and limits. If a caller has to guess whether a timeout is in milliseconds or ticks, whether the buffer must stay alive after return, or whether the call is safe from an ISR, the documentation has failed.

What the header must carry

Take a temperature sensor on I2C as the example. The datasheet says conversion takes 30 ms, the device stretches the clock, and a read during conversion returns the previous value. None of that should leak as raw register steps. It should become explicit API behaviour.

C
/* sensor.h - checked against driver v2.3, sensor rev C */
typedef enum {
    SENSOR_OK = 0,
    SENSOR_ERR_BUSY,        /* conversion in progress, retry after ready */
    SENSOR_ERR_TIMEOUT,     /* no ACK within timeout_ms, bus may need recovery */
    SENSOR_ERR_NOT_READY,   /* call sensor_init() first */
    SENSOR_ERR_ARG          /* NULL pointer or out-of-range argument */
} sensor_err_t;

typedef struct {
    int32_t temp_milli_c;   /* signed, 1 unit = 0.001 C, valid range -40000..125000 */
    uint32_t timestamp_ms;  /* driver tick at completion, wraps every 49.7 days */
} sensor_reading_t;

/* Must be called once from task context before any other call.
   Blocks up to 50 ms while the device is probed. Not ISR-safe. */
sensor_err_t sensor_init(void);

/* Starts a conversion and returns immediately. Call sensor_poll()
   until it returns SENSOR_OK. Safe from task context only. */
sensor_err_t sensor_start(void);

/* Copies the latest completed reading into *out. Returns
   SENSOR_ERR_BUSY if no conversion has finished yet.
   *out is written only on SENSOR_OK. Does not block. */
sensor_err_t sensor_poll(sensor_reading_t *out);

/* Blocking convenience wrapper: start, then poll every 5 ms
   until timeout_ms expires. timeout_ms must be >= 35.
   Task context only. The I2C bus is held for the whole call. */
sensor_err_t sensor_read_blocking(sensor_reading_t *out, uint32_t timeout_ms);

Notice what is pinned down. Units are in the type name or the comment, never left as "raw". The valid range is stated so the caller can sanity check. Ownership is clear: sensor_poll copies out, so the caller owns the struct and the driver keeps no pointer to it. Context is stated per function, because a function that blocks on a mutex or waits for an interrupt cannot run in an ISR even if it compiles there. The blocking wrapper states the bus is held, which matters when another task needs that bus.

Errors as actions, not codes

A list of error codes without guidance forces the caller back to the manual. Each code needs a recovery action and a severity.

ReturnMeaningCaller action
SENSOR_OKReading copied, fields in rangeUse the value
SENSOR_ERR_BUSYConversion still runningPoll again after at least 5 ms, do not spin
SENSOR_ERR_TIMEOUTDevice did not ACK or finish in timeRun bus recovery, then sensor_init() again
SENSOR_ERR_NOT_READYsensor_init() not called or failedFix initialisation order, do not retry the read
SENSOR_ERR_ARGNULL pointer or timeout below 35 msFix the call, this will never succeed on retry

That last column is the part most driver docs omit. It stops a caller from retrying a programming error forever, and it tells them when a timeout means the bus is wedged rather than the sensor being slow.

Lifecycle and concurrency

State that spans calls needs a diagram, because prose hides ordering bugs. For this driver the legal sequence is small enough to draw.

sensor_init OK sensor_start sensor_poll OK timeout sensor_init sensor_read_blocking Uninitialised Idle Converting Fault

Alongside it I state the concurrency rules in plain terms: one caller at a time per device instance, the driver takes an internal mutex for the bus transaction, and sensor_read_blocking holds that mutex for up to timeout_ms. If a second task calls any function while a blocking read is in progress it will block on the mutex, so the doc warns against calling the blocking form from a task with a deadline shorter than the timeout. Thread safety per instance, and whether two instances can run in parallel on different buses, gets one explicit sentence.

What stays out of the public header

Register addresses, bit fields, clock source selection and interrupt priority belong in a maintainer section or the .c file, with the datasheet revision and the board revision it was tested on. I keep a short "hardware assumptions" note there: supply range, pull-up values, and the known errata workaround, because a future engineer debugging a board spin needs it, but the API user should not need to parse it to call sensor_poll. When behaviour changes, the header version and the changelog entry change with it, and any change to units, ranges or error meanings is a breaking change that bumps the major version.

The test I apply before merging: hand the header and example to someone who has not seen the datasheet and ask them to write the polling loop. If they ask a question the header does not answer, I add the answer to the header, not to a wiki page they will never find.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-100How do you decide when work in an ISR is too much and should move to a deferred task instead?

The 90-second answer

Keep in the ISR only what must happen before the next interrupt, the next DMA transfer, or a hardware deadline. Move everything else to a task. The test is not whether the code is short. It is whether the ISR, at its worst-case rate, can still leave the CPU free for higher priority work and meet its own deadline.

I measure three things before I move code: worst-case ISR execution time, interrupt period, and the latency the work can tolerate. If the work blocks, allocates, prints, parses, or waits on a bus, it goes to a task even if it looks small. If it must acknowledge hardware or capture a timestamp, it stays.

Assume a single-core Cortex-M4 running FreeRTOS, with a 5 kHz sensor interrupt. That is a 200 µs period. Suppose the ISR currently reads the sensor, runs a filter, and formats a value for telemetry.

WorkKeep in ISR?Reason
Read status register and clear interrupt flagYesHardware may not accept the next event until cleared
Copy sample and timestamp into a bufferYes, if boundedA few dozen cycles, no blocking call
Run filter, scale, log, transmitNoVariable time, may block, can run in a task
Call a blocking I2C or UART transmitNoWaits for hardware and can overrun the period

The arithmetic that decides it

Hypothetical figures, measured with a GPIO toggle and a scope: ISR takes 38 µs worst case. At 5 kHz that is 38/200, or 19% of the CPU before any task runs. Add a 1 kHz control task that needs 210 µs every 1 ms, and utilisation is already over 40%. If the ISR grows to 120 µs, it consumes 60% and its own jitter starts to push the control task past its 500 µs deadline. That is the point to defer. I also check the tail, not the average. A path that takes 12 µs normally and 180 µs when a CRC fails will miss the period on the error path even if the average looks fine.

A second check is latency tolerance. Deferring adds queueing delay: the task runs when the scheduler picks it, not when the interrupt fires. If the task is priority 3 and a priority 4 task runs for 2 ms, the deferred work waits 2 ms. That is fine for telemetry and fatal for a 50 µs commutation deadline. So the decision is a pair: ISR time must fit the period, and deferred latency must fit the deadline.

C
/* ISR: capture and signal only. Checked against FreeRTOS 11 on Cortex-M4. */
void SENSOR_IRQHandler(void)
{
    uint32_t now = HAL_GetTick();
    uint16_t raw = SENSOR_ReadRaw(); /* bounded, no blocking call */
    SENSOR_ClearInterrupt();

    BaseType_t woken = pdFALSE;
    xTaskNotifyFromISR(sensorTask, raw, eSetValueWithOverwrite, &woken);
    portYIELD_FROM_ISR(woken);
}

void sensorTask(void *arg)
{
    uint32_t raw;
    for (;;) {
        xTaskNotifyWait(0, 0, &raw, portMAX_DELAY);
        float scaled = Filter_Update((float)raw); /* may block, log, transmit */
        Telemetry_Send(scaled);
    }
}

A queue suits this better when samples can arrive faster than the task drains them and you need to count drops. A direct task notification is cheaper and overwrites, which is right for the latest sensor value and wrong for a byte stream where every byte matters.

Yes No Yes No Interrupt fires Clear flag and capture data Next event before task can run? Stay in ISR, keep it minimal Signal task from ISR Task does slow work Queue full or task late? Count drops and raise priority or rate

Failure modes I check after deferring

The first is silent loss. xQueueSendFromISR returns errQUEUE_FULL when the queue is full. If the ISR ignores that return, samples vanish with no trace. I count overflows in the ISR and expose the counter to diagnostics.

The second is priority inversion by accident. A low priority deferred task can be starved by a medium priority task that has nothing to do with the sensor. If the deferred work has a deadline, it needs a priority that reflects that deadline, not a default.

The third is shared state. Once work moves to a task, the buffer it reads can be overwritten by the next interrupt. The ISR must write to a ring or a double buffer, or the task must copy under a short critical section. A single flag set in the ISR and cleared in the task also races if the interrupt fires between the check and the clear. I use the notification or queue as the synchronisation, not a bare flag.

I keep work in the ISR when it is bounded, short against the period, and time critical, for example clearing a flag, capturing a timer value, or pushing one byte into a ring. I defer when it can block, when its worst case threatens the period, or when its result can wait for the scheduler. That line, measured rather than guessed, is what I defend in review.

Curated: · Written: · Reviewed: —

Difficulty: Medium