Skip to content
Tech Interview Prep

Top 100 Firmware Engineer Interview Questions and Answers

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

Curated: · Written: · Reviewed: —

Reviewed 0Review pending 97

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

Q&A-1Walk me through first-day bring-up of a new board that has never run code, from power rails and reset through debugger attach and clock tree?

The 90-second answer

I bring a board up in the order the hardware can fail, and I stop at the first gate that fails. Power first, because code cannot fix a short. Then reset and boot straps, because the chip must be in a known state before a debugger can help. Then debugger attach, because that proves the debug port, flash interface and core are alive. Only then clocks, because a blinking LED at the wrong rate usually means the clock tree, not the application, is wrong.

Assume a Cortex-M4/M7 board, 3.3 V logic, SWD probe, and a schematic with the rail names and reset circuit in front of me. If the board has a PMIC or sequencer, I use its order. If it does not, I check the rails in the order the schematic powers them.

1. Power rails, unpowered then powered

With power off, I measure resistance to ground on each rail. A near-zero reading, under a few ohms on a 3.3 V rail, usually means a solder bridge, reversed capacitor or wrong component. I do not apply power to chase it.

Then I power from a bench supply with a current limit set just above the expected idle draw, for example 100 mA limit for a bare MCU board expected to draw 20 to 40 mA. I watch current before I watch voltage. A rail that sits at 0 V while drawing the limit points to a short or a disabled regulator. A rail at the right voltage with excessive current points to a downstream load.

CheckExpected on a typical 3.3 V boardWhat a failure tells me
VDD / 3V33.30 V plus or minus 5 percent, ripple under 50 mVpp0 V at limit: short or regulator off. 1.8 V: wrong divider, enable pin low, or overload
VDDA / analog rail3.30 V, quieter than digital railNoise here shows up later as ADC offset, not as a boot failure
1.8 V or 1.1 V core railPer datasheet, often sequenced after 3.3 VCore rail up before I/O rail can latch some parts into a bad state
GND to rail resistance, power offHundreds of ohms or open, part dependentSingle digit ohms: inspect, do not power

I measure at the load, not only at the regulator output, and I check enable and power-good pins. A regulator that reports good while its output is 0 V is a wiring fault, not a firmware fault.

The alternative to a bench supply is powering from USB or a wall adapter. That is faster, but the supply hides the current draw and often hides a short until the cable or connector fails. I use the bench supply for first power on a new board, and switch to the intended supply once the rails are proven.

2. Reset and boot mode

I scope NRST. It should be low while power ramps, then rise cleanly to VDD and stay there. A reset that chatters, or never releases, explains a dead core faster than any debugger session. I also check BOOT0/BOOT1 or equivalent straps. On many STM32 parts, BOOT0 high with BOOT1 low selects the system bootloader in internal flash, which is useful if main flash is blank or corrupt. On NXP and TI parts the equivalent pins select serial download mode. I record the strap state before I touch the probe, because a board that boots only in download mode will confuse every later step.

3. Debugger attach: SWD versus JTAG

I connect SWDIO, SWCLK, GND and NRST, with VTref tied to the target 3.3 V. I try a low SWD clock first, 100 kHz to 1 MHz, because a fast clock on long flying leads gives a false "cannot connect" on a healthy board. In OpenOCD or the vendor tool I read the device ID and the flash size register. If the ID matches the datasheet, the debug port, power and reset path are proven in one step.

SWDJTAG
Pins2 data/clock plus reset and ground4 to 5 pins, TMS, TCK, TDI, TDO, TRST
Speed on flying leadsReliable at 100 kHz to 1 MHz, often to 4 MHz on short leadsSimilar limit, more pins to miswire
Extra capabilityCore debug, flash, ITM/SWO traceBoundary scan, chain of devices, board interconnect test
AvailabilityDefault on most Cortex-M partsPresent on many Cortex-M, absent or fused off on some low pin count parts

I default to SWD on Cortex-M because it needs fewer connections and the probe header is usually wired for it. I switch to JTAG when SWD pins are not routed, when I need boundary scan to test a BGA or a device chain, or when SWD is disabled by option bytes but JTAG is not. If attach fails, I separate the causes. No ID at all: check VTref, ground, SWDIO/SWCLK swap, and whether the chip is held in reset. ID read but flash read fails: check boot straps and whether the part is in a locked or RDP state. Core halted at the reset vector: that is success, not failure. It means I can load a minimal image.

4. Clocks and first code

Blank flash on Cortex-M parts often starts on the internal HSI oscillator, 16 MHz on many STM32F4 parts, with the PLL off. I load a minimal C program that does nothing except enable the GPIO clock, toggle an LED, and loop. No RTOS, no UART, no interrupts yet. If the LED blinks, the core, flash, reset and at least one clock domain work.

I skip that minimal step only when a known-good image already proves the same gate, for example a vendor demo that toggles the same LED or prints on UART, or a factory programmed bootloader that answers on the serial port. Skipping it to save an hour on a board with no proven image just moves the fault into the application code.

Then I bring up the intended clock tree deliberately: confirm the external crystal oscillates with a scope or by checking the clock output pin, set the PLL multipliers and dividers from the datasheet table, switch the system clock source, and only then enable peripheral clocks. A common trap is enabling a peripheral clock before its bus divider is set, or switching to a PLL that has not locked. I verify the result by measuring a timer output or the UART baud rate, not by trusting the register write.

C
/* STM32F4 style, checked against RM0368 clock tree. HSE 8 MHz, SYSCLK 168 MHz. */
#include "stm32f4xx.h"

static void clock_init(void)
{
    RCC->CR |= RCC_CR_HSEON;
    while (!(RCC->CR & RCC_CR_HSERDY)) { }

    /* PLL: 8 MHz / 8 * 336 / 2 = 168 MHz. PLLSRC=1 selects HSE. */
    RCC->PLLCFGR = (8 << RCC_PLLCFGR_PLLM_Pos) |
                   (336 << RCC_PLLCFGR_PLLN_Pos) |
                   (0 << RCC_PLLCFGR_PLLP_Pos) |   /* /2 */
                   (7 << RCC_PLLCFGR_PLLQ_Pos) |   /* USB / SDIO / RNG */
                   (1 << RCC_PLLCFGR_PLLSRC_Pos);  /* HSE, not HSI */
    RCC->CR |= RCC_CR_PLLON;
    while (!(RCC->CR & RCC_CR_PLLRDY)) { }

    RCC->CFGR |= RCC_CFGR_HPRE1_DIV1 | RCC_CFGR_PPRE1_DIV4 | RCC_CFGR_PPRE2_DIV2;
    RCC->CFGR |= RCC_CFGR_SW_PLL;
    while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL) { }
}

int main(void)
{
    clock_init();
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN;
    GPIOD->MODER |= (1 << (2 * 12)); /* PD12 output */
    for (;;) {
        GPIOD->ODR ^= (1 << 12);
        for (volatile int i = 0; i < 2000000; i++) { }
    }
}

If PLLM were set to 16 instead of 8 with the same HSE, the PLL input would be 8 MHz / 16 = 0.5 MHz, and SYSCLK would be 0.5 MHz * 336 / 2 = 84 MHz. The LED would still blink, which is why I measure the timer output. A scope or a UART at a known baud catches a factor of two that a visual blink does not.

No Yes No Yes Power off: rail resistance Bench supply, current limit Rails in sequence? Find short or regulator fault Scope NRST and boot straps Attach SWD at low clock, read ID ID matches datasheet? Check VTref, wiring, reset, lock state Minimal blink on HSI Start HSE, lock PLL, switch SYSCLK Verify with timer or UART baud

The failure modes I name out loud in the interview are the ones that waste a day: powering a shorted rail and damaging the probe, debugging code while NRST never releases, running SWD at 4 MHz through 30 cm leads and blaming the chip, and declaring the clock tree correct because the LED blinks at roughly the right rate. Measuring the actual frequency catches the last one, and every UART and I2C timing derived from a wrong SYSCLK will be wrong with it.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-2What does volatile guarantee when polling a memory-mapped hardware status register in embedded C?

The 90-second answer

volatile tells the compiler the value behind a pointer can change without any code in the current function changing it, so it must emit a real load or store on every access. That is what makes polling a memory-mapped status register work.

C
/* C11, STM32-style UART base address */
#define UART_SR  (*(volatile uint32_t *)0x40013800UL)
#define UART_DR  (*(volatile uint32_t *)0x40013804UL)
#define TXE      (1UL << 7)

void uart_putc(char c)
{
    while ((UART_SR & TXE) == 0) {
        /* hardware sets TXE when the transmit buffer empties */
    }
    UART_DR = (uint32_t)c;
}

Without volatile, the compiler sees a loop that reads UART_SR and never writes it. It is allowed to load the value once, keep it in a register, and test that register forever. The loop then never exits even though the hardware has set the bit. With volatile, each test forces a bus read, so the loop observes the hardware change.

VersionWhat the compiler emits for the loopResult
Plain uint32_t *One load before the loop, test the cached registerHangs if TXE was clear at entry
volatile uint32_t *One load per iterationExits when hardware sets TXE

Two limits matter in an interview follow-up. volatile does not make a read atomic. A 32-bit status read split across a 16-bit bus can tear, and a flag written by an interrupt handler still needs interrupt masking or an atomic type if the main code reads it as a multi-byte value. It also does not order accesses to other memory. On ARM I would add the compiler and hardware barriers the core requires, such as __DMB() after a write that must be visible before a doorbell register is touched.

The common bug is the opposite one. Declaring every register volatile, including write-only control registers that are only written once during init, adds bus traffic for no benefit and hides the real question, which is whether each access needs to happen exactly as written. I declare volatile on status and data registers that hardware or an ISR changes, and leave plain pointers for RAM buffers the compiler is free to optimise.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-3You have a write-only 16-bit control field in the low half of a 32-bit word whose high half is a read-to-clear status register also written by an ISR: how do you set a control bit in C without clearing status or losing an ISR update?

The 90-second answer

I would not read that word at all. I keep a software shadow of the 16-bit control field, write the whole 32-bit word with the high half forced to the value that leaves the status register alone, and make the shadow update and the write atomic with respect to the ISR that touches the same word.

C
/* C11, Cortex-M4, peripheral requires 32-bit access only */
#include <stdint.h>

#define CTRL_STATUS 0x40010000u /* low 16: control (WO), high 16: status (RC) */

static volatile uint32_t *const reg = (volatile uint32_t *)CTRL_STATUS;
static uint16_t ctrl_shadow; /* only copy of control state, never read from HW */

void ctrl_set_bit(uint16_t mask)
{
    uint32_t primask;
    uint32_t word;

    __asm__ volatile ("MRS %0, primask" : "=r"(primask));
    __disable_irq();
    ctrl_shadow = (uint16_t)(ctrl_shadow | mask);
    /* High half = 0: status bits clear on write of 1, so 0 is a no-op there.
       Low half = shadow, not a read of the hardware. */
    word = (uint32_t)ctrl_shadow;
    *reg = word;
    __asm__ volatile ("MSR primask, %0" :: "r"(primask));
    __DSB(); /* write visible to peripheral before we re-enable interrupts */
}

Three constraints interact here, and each one rules out the obvious code. The peripheral requires 32-bit access, so a volatile uint16_t * write to the low half is not a shortcut. On this part it either faults or is ignored, and on parts where it appears to work it can be split by the bus into a read-modify-write inside the bridge. The control field is write-only, so *reg | mask reads back zero for the low half and clears every other control bit. The high half is read-to-clear, so any read of the full word, including the read inside a 32-bit RMW, clears pending status you have not serviced yet.

Why the shadow and the forced high half work

The shadow is the only source of truth for control. It starts at the reset value from the reference manual, not at a hardware read, and every driver path that changes control goes through it. That also fixes the write-only problem for the other bits: setting one bit writes back all 16 bits as last intended.

For the high half I write zero because this register clears on write of 1. Zero therefore preserves status. I would check that sentence in the manual before relying on it, because the opposite convention exists. If this part cleared on write of 0, a 32-bit write would clear all status and the design would be unworkable as packed. The fix then is not a cleverer mask, it is a different register map, a peripheral with separate control and status addresses, or a 16-bit access the bus actually supports. I state that assumption out loud in an interview because it is the point where the code stops being portable.

volatile on the pointer is what makes *reg = word a single observable 32-bit store. Without it the compiler could cache the word, merge it with a later write, or delete it as dead if it never reads the address back. With it, each assignment is a bus transaction. It does not make the update atomic against the ISR, which is why the critical section exists.

The ISR race, traced

Suppose control is 0x0003, status has bit 16 pending, and the ISR is about to set control bit 2 through the same shadow. Without masking:

TimeMainISRResult
1reads shadow 0x0003
2updates shadow to 0x0007, writes 0x0007
3writes stale 0x0003 | maskbit 2 lost

With interrupts masked around the shadow update and the store, the ISR either runs entirely before or entirely after. The cost is latency: the masked window is the shadow update plus one store, a few cycles, not the whole driver call. I keep it that short and I do not call anything that can block inside it.

If the ISR instead writes status through a separate clear register, it never touches the shadow, so it cannot corrupt control. If the ISR must also change control, it must use the same shadow and the same critical section, or the two writers will diverge. Two owners of one shadow is the failure mode I look for in code review.

What I check before shipping it

I confirm four things in the manual: 32-bit access only, control reads as zero, status clears on write of 1, and reserved bits in the low half must be written as zero, which the shadow satisfies only if I mask the shadow to the defined bits on every update. Then I verify on hardware with a trace probe. The bug this design prevents, a lost control bit or silently cleared status, is timing dependent and will not show up in an emulator that models the word as plain RAM.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-4How would you detect and size stack usage on a bare-metal MCU with no RTOS, and catch an overflow before it corrupts memory?

The 90-second answer

On a bare-metal Cortex-M part I treat stack as a measured budget, not a guess. I paint the whole stack at boot, scan for the watermark in idle or on a timer, put a canary at the low end, and route a guard violation to a fault handler that logs SP, PC and LR before halting. Then I size from the worst call path, not the average run.

Assume a 8 KiB main stack on an STM32F4, linker symbols _sstack and _estack, no RTOS, interrupts enabled. That setup gives me three independent signals: how much was ever used, whether we are about to overflow, and which path did it.

Painting and watermark

At reset, before main, fill the stack with 0xA5. A periodic scan from the lowest untouched word upward finds the first non-0xA5 word. Distance from _estack is the high-water mark.

C
/* Checked against GCC 12 for Cortex-M4, -O2 */
extern uint32_t _sstack, _estack;
#define PAINT 0xA5A5A5A5u

void stack_init(void) {
    for (uint32_t *p = &_sstack; p < &_estack; p++) *p = PAINT;
}

uint32_t stack_used_bytes(void) {
    uint32_t *p = &_sstack;
    while (p < &_estack && *p == PAINT) p++;
    return (uint32_t)(&_estack - p) * 4u;
}

If the scan runs every 100 ms from a timer ISR, it misses a transient peak that returns before the next scan. I therefore also sample SP in the fault and assert paths, and I run the scan in the idle loop on a busy-wait build. The number is only trustworthy if the paint happens before any C code uses the stack, which means doing it in Reset_Handler in assembly or in a __attribute__((naked)) stub before __libc_init_array.

Canary and guard

Painting tells me after the fact. A canary tells me at return time. I place a known word at the bottom of the stack, just above _sstack, and check it on every function return in critical code, or use GCC -fstack-protector-strong which inserts its own canary per function with a large frame. On mismatch, call stack_overflow_hook() which disables interrupts, writes the current SP and the corrupted canary value to a retained SRAM word, and triggers a HardFault.

For a hard stop, I add an MPU region covering the lowest 32 bytes of the stack with no access. On Cortex-M4 that raises a MemManage fault on the first push past the limit, before adjacent .data or heap is overwritten. The fault handler reads SCB->MMFSR, the stacked PC from the exception frame, and the faulting address from SCB->MMFAR when MMFSR.MMARVALID is set. That distinguishes a stack overflow from a wild pointer, which a canary alone cannot.

MethodCatchesCostBlind spot
Painting + watermarkPeak usage over timeScan O(stack) at runtime, 8 KiB scan is about 2,048 wordsMisses transients between scans
Canary / -fstack-protector-strongReturn address overwrite4 to 16 bytes per protected frame, check on returnSilent corruption if overflow jumps past the canary
MPU guard regionFirst access past limitOne MPU region, fault handler codeOnly the bottom boundary, not mid-stack overruns from a bad pointer
-fstack-usage + -Wstack-usage=256Large frames at compile timeBuild time onlyNo accounting for recursion, ISRs, or library calls like printf

Sizing the worst case

Static numbers from -fstack-usage give me a per-function frame, for example sensor_read at 96 bytes, i2c_transfer at 64 bytes, printf family at over 512 bytes on newlib-nano. I sum the deepest call chain, then add interrupt nesting. On Cortex-M, an ISR preempts main and uses the same stack unless I use MSP/PSP separation. With priority 5 timer and priority 2 UART both able to nest, worst case is main depth plus both ISRs plus the exception frame of 32 bytes per entry.

Worked example, labelled as hypothetical for a 8 KiB stack: deepest main path measured at 2,400 bytes, timer ISR 180 bytes, UART ISR 220 bytes, three nested exception frames 96 bytes, plus a 512 byte margin for printf in the error path. Total 3,408 bytes. I would set the linker stack to 4 KiB and keep the remaining 4 KiB for heap and DMA buffers, or move ISRs to PSP if the margin disappears. If the watermark ever exceeds 75 percent of the allocated stack, I treat that as a bug, not headroom, because a new error branch or a longer string format can add a frame overnight.

used > 75% triggered Reset_Handler paints stack main runs Watermark scan Log SP and caller, raise alert Canary or MPU fault stack_overflow_hook logs SP PC LR Halt or reset with retained fault record

Recursion and variable length arrays break all of this, so I ban alloca and VLAs in firmware code, cap recursion depth with an explicit counter, and audit every library call for its stack appetite. That combination, paint plus canary plus MPU guard plus a summed worst-case budget, is what I would defend in review.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-5Why is heap allocation risky in long-running firmware, and how would you design static allocation and memory pools to avoid fragmentation?

The 90-second answer

On a device with 64 KB of SRAM that must run for five years without a reboot, malloc fails in ways a server never sees. There is no MMU to recover a bad pointer, no OS to kill a leaking task, and no operator to restart the process. A general heap has three problems that compound over time: external fragmentation, unbounded allocation latency, and silent exhaustion.

External fragmentation means free memory exists but no single contiguous block fits the next request. With variable sizes and free order determined by runtime events, a 16 KB heap can fail a 512-byte allocation while 8 KB sits free in 200-byte holes. Allocation latency is also unbounded in practice. A coalescing allocator walks free lists and merges neighbours, so the same call can take 2 microseconds on a fresh heap and 400 microseconds after months of churn, which breaks a 1 ms control loop deadline. Exhaustion is the worst case. malloc returns NULL, and if the caller does not check, the firmware writes through NULL and faults in an interrupt handler with no stack trace.

My default design removes the heap from the hot path entirely. Fixed-size buffers live in static storage sized at compile time, and variable lifetime objects come from fixed-block pools with O(1) allocation.

Static allocation first

Anything with a known maximum size gets a static buffer. A 256-byte UART receive buffer, a 1,024-byte network frame, a 4,096-byte DMA descriptor ring. The linker places these in .bss, the size appears in the map file, and the cost is visible before flashing. For a 64 KB SRAM budget I would account for it explicitly: 20 KB for task stacks, 24 KB for static buffers and pools, 8 KB for the RTOS heap if one exists at all, and the rest for .data, .bss overflow and stack guard margin. If the map file shows the total crossing that budget, the build fails.

Pools for variable lifetime

Packets, messages and protocol buffers have variable lifetime but bounded size. A pool carves one contiguous arena into fixed slots and keeps an intrusive free list inside the slots themselves, so allocation is a pop and free is a push. No searching, no splitting, no coalescing, and the worst case is the same as the best case.

C
#define POOL_BLOCK_SIZE 64
#define POOL_BLOCK_COUNT 32

typedef struct Block {
    struct Block *next; /* valid only while the block is free */
} Block;

static uint8_t pool_storage[POOL_BLOCK_COUNT][POOL_BLOCK_SIZE];
static Block *free_list;
static uint32_t in_use;

void pool_init(void) {
    free_list = NULL;
    in_use = 0;
    for (uint32_t i = POOL_BLOCK_COUNT; i-- > 0;) {
        Block *b = (Block *)pool_storage[i];
        b->next = free_list;
        free_list = b;
    }
}

void *pool_alloc(void) {
    if (free_list == NULL) return NULL; /* caller must handle exhaustion */
    Block *b = free_list;
    free_list = b->next;
    in_use++;
    return b;
}

void pool_free(void *ptr) {
    Block *b = (Block *)ptr;
    b->next = free_list;
    free_list = b;
    in_use--;
}

That pool costs 32 x 64 = 2,048 bytes plus one pointer of state. Allocation touches one pointer load and one store, roughly 20 cycles on a Cortex-M4 at 168 MHz. I would run two or three size classes, for example 32, 64 and 256 bytes, rather than one large pool, because a 256-byte pool of 32 slots wastes 7 KB when the workload is mostly 48-byte messages.

ApproachWorst-case alloc timeFragmentationExhaustion behaviour
malloc / newUnbounded, grows with heap churnExternal, worsens over monthsReturns NULL, often unchecked
Static bufferZero, resolved at link timeNoneBuild fails if it does not fit
Fixed-block poolO(1), constantNone inside the poolReturns NULL at a known slot count
FreeRTOS heap_4Bounded but variableCoalescing helps, does not eliminate itReturns NULL, fragmentation still possible

Failure modes I design for

Pool exhaustion is the main one. The pool returns NULL deterministically once all 32 slots are in use, and the caller drops or queues the message instead of corrupting memory. I track in_use as a high-water mark in a debug build and assert if it stays pinned at the maximum, which usually means a leak or a missing pool_free on an error path. A second failure is a double free, which corrupts the intrusive list and hands the same slot to two owners. In development I poison freed slots with a pattern and check it on allocation. A third is size mismatch, where a 300-byte object lands in a 256-byte pool. That is a compile-time problem if the pool API takes a typed wrapper, and a code review problem otherwise.

If a heap must exist, for example for a TLS stack that demands it, I isolate it. FreeRTOS heap_1 never frees and suits a system that allocates at startup only. heap_4 coalesces adjacent free blocks and is the better default when freeing is unavoidable, but I still cap its size, log xFreeBytesRemaining periodically, and treat a falling trend over days as a leak. The heap never serves the control loop or the ISR path. Interrupts use preallocated static buffers or a lock-free ring, because a pool free list is not safe to mutate from both a task and an ISR without a critical section.

The test that convinces me is a soak run. I run the firmware for 72 hours with randomised allocation patterns, force pool exhaustion, and check that the device keeps its real-time deadlines and recovers when slots are freed. A heap that survives that test on the bench is still a liability in year three. A pool with a known slot count fails loudly, at a known point, and the rest of the system keeps running.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-6Which linker section holds uninitialised globals and statics, and what must startup code do to it before main() runs?

The 90-second answer

Uninitialised globals and statics go in .bss, and startup code must zero that region before main() runs. The C standard requires those objects to start as zero. Nothing in the flash image supplies that value, so the reset handler writes zero to every word between __bss_start and __bss_end.

That is the whole rule. If the zero loop is missing, a variable declared without an initialiser contains whatever SRAM held at power-up. On a fresh part that is often zero by luck, which hides the bug until a warm reset or a bootloader leaves stale data behind.

SectionExampleStored in flashStartup action
.dataint baud = 115200;Yes, initial value at a load address in flashCopy to RAM
.bssstatic uint8_t rx_buf[256];NoZero in RAM

The linker script defines the bounds. .bss is placed in SRAM with no flash load address, because there is no initial image to copy:

LD
.bss : {
  __bss_start = .;
  *(.bss*) *(COMMON)
  __bss_end = .;
} > SRAM

Startup code, checked against GCC 13 for ARM Cortex-M, then clears that range:

C
extern uint32_t __bss_start, __bss_end;

void Reset_Handler(void) {
    uint32_t *dst = &__bss_start;
    while (dst < &__bss_end) *dst++ = 0;

    main();
    for (;;) { }
}

Worked trace for static uint8_t rx_buf[256]; placed at 0x20000104 to 0x20000204: the loop writes 64 words of zero, covering 0x20000104 through 0x20000200. After it finishes, rx_buf[0] reads as 0 in main(), as the standard requires.

The check I run when this fails is to inspect the map file for __bss_start and __bss_end inside SRAM and confirm the reset handler references those exact symbols. A mismatch between the startup file and the linker script leaves .bss untouched, and the symptom is a global that should be zero reading as a stale value after reset.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-7Your 1 kHz PID loop reads a 32-bit encoder position and direction updated by a high-rate encoder ISR, while a UART ISR can preempt the PID loop: how do you write the ISRs and share that data without torn reads, lost counts, or blocking, and prove the timing works?

The 90-second answer

I would treat the encoder ISR as the only writer of position and direction, give it the highest priority, and make the PID loop take a consistent snapshot under a short critical section. The UART ISR runs lower and never blocks. The encoder ISR reads the pins, updates a 32-bit count, records direction in the same update, clears its interrupt source, and returns. No parsing, no UART transmit, no waiting for a flag. If the ISR waits, it masks everything below it and, on a GPIO encoder, edges arriving while it runs can coalesce into one pending bit and be lost.

volatile alone does not solve this. It stops the compiler caching the variable in a register, but it does not stop a torn read of a 32-bit value, a read-modify-write lost update, or the PID loop reading position from one encoder step and direction from the next. Those need atomicity, not just visibility.

The constraints that interact

Assume a Cortex-M4 at 168 MHz, a quadrature encoder producing up to 20,000 edges per second in the worst case, a PID loop at 100 Hz, and a UART receive ISR that can preempt the PID loop but not the encoder. Edge interval at worst case is 50 microseconds. The critical section that protects the snapshot must be far below that, or encoder edges queue up behind it. The encoder ISR itself must also be far below 50 microseconds, or it becomes the bottleneck.

PathBudget (hypothetical, measured on scope)Consequence if exceeded
Encoder ISR entry to exit0.8 us, about 135 cyclesAt 20 kHz edges, 1.6% CPU, 0.8 us added latency to lower priorities
Snapshot critical section0.15 us, about 25 cyclesEncoder edge delayed by at most 0.15 us, no coalescing at 50 us interval
UART ISR1.2 us per bytePreempts PID, never encoder, drops byte on ring overrun instead of blocking
PID loop period10 msSnapshot cost is negligible, consistency matters more than speed

I measure the ISR with a GPIO toggled on entry and exit. Worst case is checked with the motor at maximum speed and UART at full rate, because average timing hides the collision.

Consistent snapshot, not two separate reads

Packing direction into the update matters. If the ISR writes position and then direction, and the PID loop reads them in between, the loop computes velocity with a position from step N and a sign from step N+1. The error is small at low speed and becomes a visible glitch at direction reversal, exactly where the PID is most sensitive.

C
/* GCC 13, Cortex-M4, -O2. Encoder ISR is highest priority. */
static volatile int32_t encoder_pos;
static volatile int8_t  encoder_dir; /* +1 or -1, written in same ISR */

void Encoder_IRQHandler(void)
{
    /* Read pins, decode quadrature, then: */
    encoder_pos += encoder_dir;
    /* Clear the GPIO interrupt pending bit here, before exit. */
    /* Leaving it set causes immediate re-entry. */
}

static void encoder_snapshot(int32_t *pos, int8_t *dir)
{
    uint32_t primask = __get_PRIMASK();
    __disable_irq();
    *pos = encoder_pos;
    *dir = encoder_dir;
    __DMB();
    __set_PRIMASK(primask);
}

Saving and restoring PRIMASK matters. A blind __enable_irq() at the end re-enables interrupts even if the PID loop called this from inside a deeper critical section, which silently breaks that outer protection. The __DMB() orders the reads before the restore on Cortex-M, where the compiler and the bus can otherwise reorder accesses around the barrier.

The alternative is a sequence counter: the ISR increments a version before and after the update, and the reader retries if the version changed or is odd. That avoids masking interrupts entirely, which helps if the critical section ever grows. I prefer the critical section here because the protected region is two loads, the retry loop in a seqlock can livelock under a 20 kHz writer, and the PID loop runs at 100 Hz so a 0.15 us mask is cheap. I would switch to a seqlock or to a hardware quadrature timer counter, read as a single register, if the snapshot grew to a struct or if edge rate rose another order of magnitude.

Why the UART ISR stays out of the way

The UART ISR moves one byte into a single-producer ring buffer and returns. Head is written only by the ISR, tail only by the main loop, both are single bytes, so no lock is needed. On overrun it increments a counter and drops the byte. Blocking to wait for space would hold off the PID loop for the duration of a UART frame and, if the UART priority were ever raised above the encoder, would lose encoder edges. Priority assignment is part of the design: encoder highest, UART next, SysTick and PID task lowest. On NVIC, that means the encoder priority value must be numerically lower than the UART value under the priority grouping in use, and I verify it in the register rather than trusting the HAL default.

Encoder edge Encoder ISR: update pos and dir PID snapshot under PRIMASK PID calculation UART byte UART ISR: push to ring Main loop: drain ring

The failure modes I would name in the interview are torn reads, lost increments from a read-modify-write interrupted by the ISR, mismatched position and direction, immediate re-entry from an uncleared interrupt source, and lost encoder edges when a lower priority ISR or a long critical section delays the encoder ISR past the next edge. Each one has a concrete check: snapshot under a saved PRIMASK, clear the source in the ISR, keep the ISR under a microsecond, and count overruns so silent data loss becomes a visible counter.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-8Your motor timer ISR must run every 1 ms and finish within 20 µs, but a CAN receive ISR takes 180 µs: how do priorities and nesting decide whether the timer is delayed, and what would you change in the CAN handler?

The 90-second answer

Assume a Cortex-M4 at 168 MHz with NVIC preemption priorities enabled. Give the 1 kHz timer the highest preemption priority and CAN a lower one. With interrupts enabled inside the CAN handler, the timer preempts it, runs for 10 µs, and returns. The timer is delayed only by hardware entry, about 12 cycles or 70 ns, plus any time the CAN handler spends with interrupts masked. That masked time is the usual cause of a missed deadline. A CAN handler that disables interrupts for 180 µs blocks the timer for 180 µs, whatever the priority numbers say.

Priority decides which handler can interrupt which. On Cortex-M the preemption priority field does that work. The subpriority field only orders pending handlers that share the same preemption priority. It never causes preemption. So two handlers at the same preemption priority run to completion in priority order, and a long one delays the other by its full execution time.

TimeEventTimer delay
0 µsCAN ISR starts at priority 2, interrupts enabled0 µs
40 µsTimer compare fires at priority 0 and preempts CAN0.1 µs entry
50 µsTimer ISR finishes and returns to CAN10 µs total
180 µsCAN ISR finishesdeadline met
0 µsSame trace, CAN masks interrupts for 180 µs180 µs
180 µsTimer is finally taken20 µs deadline missed

Two fixes keep the CAN work from blocking the timer. The first is to make the CAN handler preemptible and short. The second, which I prefer, is to move the work out of the handler entirely. Copy the received frame into a ring buffer, clear the hardware receive flag, and return. Parsing and forwarding run in thread context. That trades a few milliseconds of extra latency for CAN data, which the application can usually tolerate, for a CAN handler that takes a few microseconds and cannot delay the timer beyond its entry time.

C
/* Cortex-M, CMSIS. Lower number means higher preemption priority. */
#define PRIO_TIMER  0u
#define PRIO_CAN_RX 2u

void board_init_interrupts(void)
{
    NVIC_SetPriority(TIM2_IRQn, PRIO_TIMER);
    NVIC_SetPriority(CAN1_RX0_IRQn, PRIO_CAN_RX);
    NVIC_EnableIRQ(TIM2_IRQn);
    NVIC_EnableIRQ(CAN1_RX0_IRQn);
}

void CAN1_RX0_IRQHandler(void)
{
    can_frame_t f;
    can_read_rx(CAN1, &f);   /* also clears the RX flag */
    ring_push(&can_ring, &f);
}

void TIM2_IRQHandler(void)
{
    control_step();
}

The ring has one producer, the CAN ISR, and one consumer, thread context. Updating head and tail in a fixed order makes that safe without a lock. If thread code also pushes to the same ring, add a short critical section around the index update only. Keep that section to a few instructions. Masking interrupts across a peripheral read, a loop, or a library call is what turns a 70 ns entry into a 180 µs delay.

CAN frame arrives CAN ISR copies frame to ring Thread parses and forwards Timer compare Timer ISR runs control step

Assign priorities by deadline. The timer has a hard 20 µs deadline every 1 ms, so it sits at priority 0. CAN data can usually wait 1 to 5 ms, so it sits lower and its processing is deferred. Check the result with a GPIO toggled at timer ISR entry and a scope under full bus load. If the timer still misses, the trace shows whether masking, equal priorities, or a shared resource caused it, and each cause needs a different fix.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-9A timer ISR increments a 32-bit sample counter while a task reads it and occasionally sees torn values: how do you diagnose that race and fix it?

The 90-second answer

Assume an ATmega328P, an 8-bit AVR at 16 MHz, a Timer1 ISR at 1 kHz incrementing a 32-bit sample counter, and main-loop code reading that counter to compute a rate. If the rate occasionally spikes by about 256 or 65536, suspect a torn read before suspecting the sensor.

volatile stops the compiler caching the counter in a register or reordering accesses around it. It does not make a 32-bit access atomic. On this AVR the compiler emits four byte loads for a 32-bit read, and four byte loads plus stores for sample_count++. An ISR can fire between any two of those bytes.

C
volatile uint32_t sample_count; /* written only in ISR */

ISR(TIMER1_COMPA_vect) {
    sample_count++;
    /* clear timer flag */
}

void loop(void) {
    uint32_t now = sample_count; /* four byte loads on AVR */
    uint32_t delta = now - prev;
    prev = now;
}

Worked trace, counter at 0x0000FFFF, little-endian bytes FF FF 00 00:

StepISRReaderBytes assembled by reader
1reads byte 0FF
2increments to 0x00010000
3reads bytes 1 to 300 01 00
4assembles value0x000100FF = 65791, not 65536

The reader gets a value the counter never held. delta is then 255 too large for that sample. Diagnosis: in a debug build, read the counter twice in the reader and log when the two reads differ, or toggle a GPIO around the read and check on a logic analyser whether the ISR lands inside that window. A watchpoint on sample_count that breaks on ISR writes while the reader is mid-copy shows the same thing.

Fix 1: critical section for a short copy.

C
uint32_t read_count(void) {
    uint8_t saved_sreg = SREG;
    cli(); /* AVR: clear global interrupt enable */
    uint32_t v = sample_count;
    SREG = saved_sreg; /* restores I flag, not just sei() */
    return v;
}

Restoring SREG matters. A bare sei() would re-enable interrupts even if the caller had them disabled. The copy is four LDS instructions, roughly 8 to 12 cycles on AVR, under 1 us at 16 MHz. Use this when the shared data is a few bytes and the reader only needs the latest value. Keep the section to the copy. Putting the rate calculation, a serial print, or a wait inside it stretches interrupt latency by that whole duration and can make the ISR miss its deadline.

Fix 2: sequence counter, no masking.

The ISR increments a sequence byte before and after updating a wider sample, and the reader retries if the sequence changed or is odd during its copy. This adds no interrupt latency and suits a reader that can tolerate a retry. It needs a retry loop with a bound, and it still only gives the latest sample. A single boolean flag is not enough here: if the ISR fires twice before the reader clears the flag, two events collapse into one. Use a counter flag if every event must be counted.

Fix 3: ring buffer written by the ISR.

C
void Timer_ISR(void) {
    uint32_t v = ++sample_count;
    ring_push(&samples, v); /* ISR-safe: single producer, head written only here */
}
Timer ISR Ring buffer in static RAM Main loop Compute rate

The ring preserves order and every sample until it fills. Size it from the rates, not by guess. At 1 kHz, a main loop that runs every 10 ms consumes about 10 samples per pass, so a 32-entry buffer holds roughly 32 ms of samples if the loop stalls. Check the push return value and count overflows, because a full ring drops data by design. This costs a copy per sample and static RAM, and it is the right choice when the reader is bursty or slower than the ISR and must not miss events.

ApproachAdded ISR latencyEvery sample keptBest when
Critical sectionUnder 1 us for a 4-byte copy at 16 MHzNo, latest value onlySmall shared state, latest value is enough
Sequence counterNear zeroNo, latest value onlyReader can retry and masking interrupts is costly
Ring bufferOne copy per sampleYes, until fullReader is bursty or slower than the ISR

Rule I apply: copy under a critical section if the data fits in a few bytes and only the current value matters. Move to a ring buffer when events must not be lost or processing takes longer than the ISR period. Never share a multi-field struct between ISR and main code on volatile alone, because volatile keeps each field fresh but does not keep the fields consistent with each other.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-10When a low priority task holds a mutex that a high priority task needs, what does priority inheritance do to the holder's priority?

The 90-second answer

Priority inheritance temporarily raises the priority of the low priority task that holds the mutex to the priority of the highest priority task waiting for it. The holder then runs ahead of medium priority tasks, finishes its critical section, releases the mutex, and returns to its own priority.

That one rule bounds priority inversion. Without it, a high priority task can wait for a medium priority task that does not even use the mutex. With it, the high priority task waits only for the holder to finish the short section it was already in.

Concrete scenario

Three tasks share a UART mutex. Higher number means higher priority.

TaskPriorityUses UART mutex
H control loop30Yes
M logger20No
L telemetry10Yes

Trace:

TimeEventRunning task
0 msL locks the mutex and starts sendingL
0.05 msH wakes and blocks on the mutexL
0.05 msKernel raises L from 10 to 30L
0.06 msM wakes at priority 20, cannot preempt LL
0.10 msL unlocks, drops back to priority 10H

Without inheritance, M would preempt L at 0.06 ms and H would wait for the whole logger loop, perhaps 10 ms. With inheritance, H waits about 50 microseconds, the time L needs to finish sending.

L holds mutex at priority 10 H blocks on mutex at priority 30 Kernel raises L to 30 L finishes and unlocks H runs, L returns to 10

In code

On FreeRTOS, a mutex created with xSemaphoreCreateMutex() inherits. A binary semaphore does not, even though the take and give calls look the same.

C
/* FreeRTOS 11.1.0, configUSE_MUTEXES = 1 */
SemaphoreHandle_t uartMutex = xSemaphoreCreateMutex();

void telemetry_task(void *arg)
{
    for (;;) {
        xSemaphoreTake(uartMutex, portMAX_DELAY);
        uart_write(buffer, 256);
        xSemaphoreGive(uartMutex);
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

Priority ceiling is the related alternative. The mutex has a preset ceiling, usually the highest priority of any task that locks it, and the holder jumps to that ceiling as soon as it locks. Inheritance reacts to an actual waiter. Ceiling reacts at lock time. Both stop a medium priority task from delaying the holder, and both only help if the critical section stays short and does not block on something else while the mutex is held.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-11Battery-powered Cortex-M must meet a 10 ms sensor deadline, keep a 1 kHz ISR jitter under 50 µs, and sleep in tickless idle: how do you pick preemptive vs cooperative scheduling and configTICK_RATE_HZ, and what breaks if the sensor task never blocks?

The 90-second answer

I would run preemptive scheduling with time slicing on, set configTICK_RATE_HZ to 100, and keep the 1 kHz control work in a hardware timer ISR rather than a FreeRTOS task. That split is what makes the three constraints coexist. A 1 kHz FreeRTOS tick would wake the part every millisecond, which defeats tickless idle, and it would add SysTick and context switch overhead inside the control period. A 100 Hz tick gives 10 ms resolution, which matches the sensor deadline, and lets the CPU sleep between ticks.

Cooperative scheduling (configUSE_PREEMPTION 0) would be the wrong default here. It only switches when a task blocks or yields, so the logger at lower priority depends entirely on the sensor task cooperating. Preemptive scheduling contains a misbehaving task to the priorities below it, but it does not fix a sensor task that never blocks. That task still starves the logger and the idle task in either mode.

ChoiceEffect on this design
Preemptive, time slicing onTick can switch to a higher priority ready task. Equal priority tasks round robin.
CooperativeTick increments but does not switch. A task runs until it blocks or calls taskYIELD().
configTICK_RATE_HZ 10001 ms timeout resolution. SysTick every 1 ms, tickless idle rarely sleeps.
configTICK_RATE_HZ 10010 ms resolution. SysTick every 10 ms, sleep windows of several ms.
1 kHz work as FreeRTOS taskSubject to scheduling delay and tick jitter.
1 kHz work as timer ISRFixed latency from the timer, no scheduler in the path.

Tick, jitter, and sleep arithmetic

Assume a 168 MHz Cortex-M4, a 1 kHz timer ISR that must start within 50 microseconds of the timer edge, and a sensor deadline of 10 ms. Hypothetical but checkable figures: the SysTick handler plus a context switch costs about 3 to 5 microseconds in the FreeRTOS port, and a blocked task wakeup adds a few more. At 1000 Hz that overhead repeats every millisecond and the part wakes from sleep at least 1000 times per second. At 100 Hz it repeats every 10 ms, which aligns with the sensor period, and configUSE_TICKLESS_IDLE can suppress the tick when the next wakeup is more than configEXPECTED_IDLE_TIME_BEFORE_SLEEP ticks away.

C
/* FreeRTOSConfig.h, FreeRTOS 11.x */
#define configUSE_PREEMPTION                 1
#define configUSE_TIME_SLICING               1
#define configTICK_RATE_HZ                   ((TickType_t)100)
#define configUSE_TICKLESS_IDLE              1
#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 5

The 1 kHz ISR stays outside the scheduler. It reads the encoder or ADC, runs the control math, and if it produces data for a task it uses xQueueSendToBackFromISR followed by portYIELD_FROM_ISR. I would measure jitter with a GPIO toggled at ISR entry and a scope or logic analyser, because a claim of under 50 microseconds needs a trace, not a calculation. If the ISR itself takes 20 microseconds, the remaining budget is for interrupt latency and any higher priority ISR that can preempt it.

Timer ISR 1 kHz Control math in ISR FromISR queue send Sensor task 100 Hz Logger task low priority SysTick 100 Hz

What breaks when the sensor task never blocks

Trace the failure with sensor at priority 3, logger at priority 1, and idle at priority 0. The sensor loop polls a register with no delay, queue send, or yield.

TimeCooperativePreemptive, 100 Hz tick
0 mssensor runssensor runs
10 ms tickTick counts, no switch, logger still waitingTick fires, sensor is highest ready, keeps CPU
50 msLogger queue fills, samples droppedSame, logger starved
500 msIdle never runs, tickless idle never entered, watchdog riskIdle never runs, same watchdog risk

The subtle point is that the two modes fail differently for equal priority work. In cooperative mode a same priority task also never runs. In preemptive mode with time slicing, equal priority tasks do alternate each tick, so a peer task survives while the logger below the busy task still starves. Neither mode rescues lower priorities from a busy high priority loop.

The fix is to make the sensor task block on its own period:

C
void sensor_task(void *arg) {
    TickType_t next = xTaskGetTickCount();
    for (;;) {
        read_register();
        xQueueSendToBack(queue, &sample, portMAX_DELAY);
        next += pdMS_TO_TICKS(10);
        vTaskDelayUntil(&next, pdMS_TO_TICKS(10));
    }
}

vTaskDelayUntil keeps the 10 ms period stable even if the read takes 2 ms, and the block gives the scheduler a switch point and the idle task a chance to enter sleep. I would feed the watchdog from the idle task or from a monitor that checks the logger heartbeat, so a starved logger trips the watchdog instead of failing silently. If a driver genuinely cannot tolerate preemption, I would protect it with a critical section or a mutex with priority inheritance, and keep that section short, rather than switching the whole system to cooperative scheduling.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-12Define deadline, period, jitter and WCET, and how would you argue a task meets its deadline under worst-case load?

The 90-second answer

Period is when a task is released, deadline is when it must finish relative to that release, jitter is how much its actual release varies from the ideal periodic instant, and WCET is the longest time the task can take on the target hardware under the worst input and hardware state. A task meets its deadline when its worst-case response time, including preemption by higher priority work and blocking by lower priority work, stays at or below the deadline. I would not argue that from average timing. I would show a response time calculation with measured or statically bounded WCETs, then confirm it with worst-case traces on the board.

TermMeaningFirmware example
Period TMinimum interval between releasesControl task released every 1,000 µs
Deadline DLatest completion time after releaseMust finish within 1,000 µs, or 200 µs for a hard sub-deadline
Release jitter JVariation in release time from the ideal tickTick ISR delayed by a higher priority ISR, so release varies by 0 to 15 µs
WCET CUpper bound on execution timePID computation takes at most 120 µs on a 168 MHz Cortex-M4 with flash wait states configured

Response time under load

For fixed priority preemptive scheduling, the worst case for a task i is usually the critical instant: it is released together with all higher priority tasks, and a lower priority task has just entered a critical section. Iterate:

R(i) = C(i) + B(i) + sum ceil((R(i) + J(j)) / T(j)) * C(j)

B(i) is blocking from a lower priority critical section, J(j) is jitter of each interfering task j. Start with R = C + B, repeat until it stops growing or exceeds the deadline.

Worked example, hypothetical but sized like a motor controller. Control task: T = 1,000 µs, D = 1,000 µs, C = 120 µs. It is preempted by a current-loop ISR task with T = 250 µs, C = 30 µs, J = 10 µs. A lower priority logger holds a shared bus lock for at most B = 40 µs.

IterationCalculationR
1120 + 40 + ceil((160 + 10)/250) * 30190 µs
2120 + 40 + ceil((190 + 10)/250) * 30190 µs

R = 190 µs, well under D = 1,000 µs. The margin is not the point. The point is the bound accounts for the bus lock and the jittered ISR. If the logger lock grew to 900 µs, the same arithmetic fails, and no amount of average-case measurement would rescue it.

C
// Cortex-M4, DWT cycle counter. Measure on target, not in simulation.
static inline uint32_t cycles_now(void) { return DWT->CYCCNT; }

uint32_t t0 = cycles_now();
pid_step();
uint32_t elapsed = cycles_now() - t0;
if (elapsed > wcet_budget_cycles) { /* record, flag, do not silently continue */ }

Where WCET comes from

Measurement alone gives a lower bound on WCET, because the test may never hit the worst path. I combine three sources. First, static or semi-static analysis of the binary for the hot loop, with cache and flash wait states modelled. Second, targeted measurement: force maximum input range, maximum CAN frame queue, DMA active, flash read during a write, and interrupts enabled, then record the maximum over a long soak. Third, a runtime guard: a deadline monitor that timestamps release and completion and increments a counter on overrun. The counter is the evidence in the field. If it stays at zero during a worst-case soak, the argument holds. If it moves, the model was wrong.

Jitter needs the same treatment. If a task is released by a timer ISR, jitter equals the ISR delay from higher priority interrupts plus timer clock tolerance. I would measure release timestamps against the timer compare value over 100,000 periods and use the observed maximum in the calculation, not the nominal zero.

Failure modes I check before claiming it passes

Priority inversion if a mutex lacks priority inheritance, unbounded blocking if an ISR disables interrupts around a long copy, and WCET growth when code moves from RAM to flash or when a compiler update changes inlining. Each one invalidates the numbers above. The fix is to re-measure C and B after any change to the build, clock tree, or interrupt mask, and to keep the response time calculation in the design record next to the measured maxima. That is the argument an interviewer can probe: definitions, a calculation that closes, and a measurement plan that would catch the calculation being wrong.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-13How would you design a watchdog strategy that catches a hung task but does not reset the device during a legitimate multi-second flash erase?

The 90-second answer

Do not let any application task feed the hardware watchdog directly. Each task checkpoints a timestamp, a supervisor task checks every checkpoint against its deadline, and only the supervisor feeds the independent watchdog when every task is inside its deadline. A hung task then stops checkpointing, the supervisor stops feeding, and the independent watchdog resets the part. Feeding from the task itself defeats the purpose, because a task stuck in a loop that still reaches its feed call looks healthy.

The flash erase problem is solved by making the erase visible to the supervisor, not by disabling the watchdog. The erase driver erases in chunks, checkpoints after each chunk, and sets a progress counter. The supervisor grants an extended deadline only while the operation state is ERASE_IN_PROGRESS and the progress counter is advancing. If erase stalls, progress stops, the extended deadline expires, and the watchdog fires. If erase is progressing normally, no false reset occurs.

Mechanism

Use the independent watchdog, clocked from its own low-speed oscillator, not the system clock. On an STM32-class part the IWDG runs from the 32 kHz LSI even if the PLL or HSE fails, which is exactly the failure you want to catch. Size it from the worst legitimate gap between supervisor feeds, plus margin for clock tolerance.

Example arithmetic, labelled as a worked example: LSI at 32 kHz, prescaler 256 gives a 125 Hz counter, 8 ms per tick. Reload value 750 gives 6.0 s. That covers a supervisor period of 100 ms with a large margin, and it covers one internal flash sector erase of about 100 ms to 1 s depending on the part. For an external NOR flash where a 64 KiB sector erase takes up to 4 s at temperature extremes, chunk the erase and checkpoint per sector, so the supervisor never needs a deadline longer than one sector time plus margin. A single 6 s timeout with no chunking would also work for one sector, but it would delay detection of a hang that starts just before the erase by up to 6 s.

Add a window watchdog if the platform has one, or emulate the window in the supervisor. The window catches a different failure: code spinning in a tight loop that feeds the watchdog far too fast, for example a corrupted loop that never reaches the real work. The supervisor feed must land inside the window, not just before the timeout.

C
/* Checked against FreeRTOS-style tick, 1 ms tick. Bare metal is the same shape. */
#define TASK_COUNT 4

static volatile uint32_t last_checkpoint_ms[TASK_COUNT];
static volatile uint32_t erase_progress;      /* sectors completed */
static volatile uint32_t erase_last_progress_ms;
static volatile bool     erase_in_progress;

void task_checkpoint(int id)
{
    last_checkpoint_ms[id] = tick_ms();
}

/* Erase driver: never blocks the supervisor for a whole chip erase. */
void erase_sector_and_checkpoint(uint32_t sector)
{
    flash_erase_sector(sector);   /* may take up to 4 s on external NOR */
    erase_progress = sector + 1;
    erase_last_progress_ms = tick_ms();
    task_checkpoint(TASK_ERASE);
}

void supervisor_task(void)
{
    for (;;) {
        uint32_t now = tick_ms();
        bool healthy = true;

        for (int i = 0; i < TASK_COUNT; i++) {
            uint32_t deadline = task_deadline_ms[i];
            if (i == TASK_ERASE && erase_in_progress) {
                /* Extended deadline only while progress is advancing. */
                if (now - erase_last_progress_ms > ERASE_STALL_MS)
                    healthy = false;
                continue;
            }
            if (now - last_checkpoint_ms[i] > deadline)
                healthy = false;
        }

        if (healthy)
            iwdg_feed();   /* only place in the system that feeds it */

        vTaskDelay(pdMS_TO_TICKS(50));
    }
}

Note what the erase branch does not do. It does not feed the watchdog from inside the erase loop, and it does not suspend the watchdog for the duration. A feed inside flash_erase_sector polling loop would keep the part alive even if the flash status register never clears, which is a real hang mode on external NOR parts. The stall check catches that: progress stops advancing, ERASE_STALL_MS expires, feeding stops.

Deadlines

TaskCheckpoint periodDeadlineNotes
Control loop1 ms10 msMissed deadline means scheduling or ISR fault
Comms10 ms100 msUART and CAN handlers checkpoint from task context, never from ISR
Logging50 ms500 msLowest priority, longest deadline
Eraseper sector5 s stall limitExtended only while erase_in_progress and progress advances
Supervisor50 msfeeds IWDG at 6 s timeoutWindow check rejects feeds faster than 1 s

Failure modes worth naming

A reset during a flash erase can corrupt the sector being erased and, on some parts, leave the flash controller in a state where the next boot reads garbage. That is why the timeout must exceed the worst case erase time at the lowest operating temperature, taken from the flash datasheet, not the typical value. If the erase genuinely cannot finish inside the watchdog window, chunk it across supervisor cycles or use a two-stage approach: erase to a scratch sector first, verify, then commit.

Clock drift matters. LSI tolerance can be plus or minus 10 percent or worse across temperature on some parts, so a nominal 6 s timeout can be 5.4 s. Keep the margin between the longest legitimate gap and the timeout at least twice the drift, and measure the actual LSI frequency on the board during bring-up.

A hung supervisor is the blind spot. If the supervisor itself hangs, it stops feeding, so the watchdog still fires. That is the point of keeping the supervisor small and free of blocking calls. It must never call a driver that can block, including the flash driver. The erase task does the blocking work and only reports progress.

Yes No, erase progressing No, stalled or hung Task checkpoints timestamp Supervisor reads all timestamps All inside deadline? Feed independent watchdog Stop feeding Watchdog resets part

On reset, record the cause before clearing it. Read the reset flags, store the last checkpoint timestamps and the erase progress counter in a no-init section or retained RAM, and log them on the next boot. Without that, every field reset looks identical and you cannot tell a hung comms task from a stalled erase.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-14On a cached Cortex-M7, what cache operation do you perform on a transmit buffer before DMA starts, and on a receive buffer before the CPU reads it after DMA completes?

The 90-second answer

DMA writes to SRAM directly and bypasses the CPU cache on a Cortex-M7. The CPU therefore has to move data between cache and SRAM at each handover. Clean the cache lines before a transmit transfer starts, so the bytes the DMA engine reads from SRAM are current. Invalidate the cache lines before the CPU reads a receive buffer after the transfer completes, so the CPU discards stale cached copies and fetches the bytes DMA wrote.

That pair of operations is the whole rule. Cleaning pushes dirty cache lines out to SRAM. Invalidating marks cache lines as not present, so the next CPU read misses and loads fresh data from SRAM.

C
/* Cortex-M7, 32-byte cache line, buffer in DMA-reachable SRAM */
#define CACHE_LINE 32u

__attribute__((aligned(CACHE_LINE)))
static uint8_t buf[CACHE_LINE];

void start_tx(void)
{
    __DSB();
    SCB_CleanDCache_by_Addr(buf, CACHE_LINE);
    __DMB();
    dma_start(buf, CACHE_LINE);
}

void on_rx_complete(void)
{
    __DMB();
    SCB_InvalidateDCache_by_Addr(buf, CACHE_LINE);
    __DSB();
    process(buf, CACHE_LINE); /* CPU reads now see DMA data */
}

__DSB() waits for the cache operation to finish before execution continues. __DMB() orders memory accesses so the DMA engine is not started until the clean has taken effect. The same ordering applies in reverse on receive.

DirectionWhenOperationEffect if omitted
TransmitAfter CPU fills buffer, before DMA startClean by addressDMA sends old SRAM contents, possibly zeros on first use
ReceiveAfter DMA complete interrupt, before CPU readsInvalidate by addressCPU reads stale cached bytes from before the transfer

Alignment supports the rule. The buffer should start on a cache line boundary and occupy whole lines, because clean and invalidate act on entire lines. A buffer sharing a line with another variable causes that variable to be cleaned or invalidated along with the buffer. Keeping the buffer line-aligned and padded to a multiple of 32 bytes avoids that side effect.

CPU fills TX buffer Clean cache lines DMA reads SRAM DMA writes SRAM Complete interrupt Invalidate cache lines CPU reads fresh data

A common symptom helps confirm the diagnosis. Transmit data that is correct in a debugger memory view but wrong on the wire points to a missing clean. Receive data that matches the previous frame points to a missing invalidate. Both faults can pass on a core with the cache disabled, which is why they often appear only after cache enablement in a later build.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-15Your SPI flash reads are mostly correct but corrupt intermittently at higher clock rates: how do you isolate whether it is CPOL/CPHA, clock rate, or chip-select timing using a logic analyzer?

The 90-second answer

I capture a passing transfer and a failing transfer with the same fixed payload, decode both directions, and classify the error before touching driver settings. A CPHA mismatch produces a deterministic one-bit shift. A CPOL mismatch usually inserts or drops a clock edge at the start of the frame. A clock-rate problem appears only above a threshold. A chip-select problem truncates the first or last byte, or splits one command into several frames. Those signatures point to different fixes, and changing settings blindly mixes them up.

I send A5 3C C3 5A repeatedly, enable CRC or a checksum in the flash read command if the device supports it, and log which transfers fail. Then I repeat at half the clock and with a longer CS setup delay. If halving the clock fixes it, timing or signal integrity is marginal. If the same shifted bytes appear at every clock, the mode is wrong. If only the first byte after idle is bad, CS setup is too short.

Mode mismatch, derived

CPOL sets the idle level of SCLK. CPHA selects whether the first data bit is presented before the first edge (CPHA=0) or after it (CPHA=1). Sampling happens on the opposite edge to the one that changes the data.

ModeCPOLCPHAIdle SCLKSample edge
000lowrising
101lowfalling
210highfalling
311highrising

Take a master in mode 0 sending A5 3C, that is 10100101 00111100. It presents the first 1 before the first rising edge and samples on rising edges. A slave expecting mode 1 samples on falling edges, the second edge of each pair. It therefore never sees the first 1. It captures bits 2 to 8 of A5, which are 0100101, then the first bit of the next byte, 0. The decoded byte is 01001010, or 4A. Every byte shifts left by one position and picks up the next byte's first bit. That exact pattern on the analyzer is a CPHA mismatch, not noise.

The reverse case differs. A master in mode 1 changes data on the first edge, so a mode 0 slave sampling on that same edge can capture the new bit or the old bit depending on setup and hold times. The result is often the first bit wrong and the rest correct, or a race that varies with clock rate. A CPOL mismatch is different again. If the master idles high and the slave expects idle low, the slave may count the initial transition as a clock edge and start sampling one edge early, which can add a spurious leading bit. So a clean one-bit shift across all bytes implicates CPHA. An extra leading bit implicates CPOL.

I also check dummy cycles separately. Many flash read commands insert dummy clocks after the address before data appears. If the driver omits them, MOSI decodes correctly and MISO looks shifted by the dummy count. That is a protocol error, and changing CPHA to compensate breaks MOSI.

C
/* STM32F4 SPI1_CR1, checked against the reference manual. */
uint32_t cr1 = SPI1->CR1;
uint32_t cpha = (cr1 >> 0) & 1u;
uint32_t cpol = (cr1 >> 1) & 1u;
uint32_t baud_div = (cr1 >> 3) & 0x7u; /* BR[2:0], PCLK2 / 2^(div+1) */
uint32_t spe  = (cr1 >> 6) & 1u;
(void)cpha; (void)cpol; (void)baud_div; (void)spe;

Reading the register matters because driver abstractions hide mismatches. Several vendors order their mode enums differently from the datasheet table, and a copied init routine can run mode 3 while the comment says mode 0.

Clock rate and signal integrity

If decoding is correct at 8 MHz and corrupt at 25 MHz, I compare the clock against the slave limits: maximum SCLK, minimum period, and data setup and hold around the sampling edge. A hypothetical part rated at 20 MHz maximum will fail at 25 MHz even though many transfers pass, because the margin depends on voltage, temperature, and probe loading. Intermittency that grows as the board warms up fits this pattern.

On the analyzer I look for ringing that crosses the threshold twice, slow rise times, and reflections. I use a short spring ground, since a long ground lead invents ringing the real signal does not have. If ringing appears only when a nearby motor driver switches, coupling is the cause. Lowering the clock is the fastest fix and the right choice when the throughput budget allows it, for example dropping from 25 MHz to 12.5 MHz still leaves ample margin for a 1 MB/s logging stream. A series resistor of 22 to 47 ohms at the master output is the better choice when the clock must stay high and the ringing is local to the MOSI or SCLK trace. Re-routing or a shorter trace is the better choice when ringing appears on multiple lines and at the slave end, because a resistor at the master will not fix a stub at the far end.

Yes No Yes No Yes No Capture passing and failing transfers Decode MOSI and MISO per CS frame All bytes shifted by one bit? Fix CPHA or dummy cycles Extra leading bit or truncated frame? Check CPOL and CS timing Only fails above a clock threshold? Check max SCLK and signal integrity Check DMA length and buffer lifetime

Chip-select timing

CS faults leave a different trace. CS rising before the last clock edge truncates the final byte. CS falling with the first clock arriving a few nanoseconds later violates the slave CS setup time, often 10 to 20 ns in flash datasheets, and the first bit is missed. CS toggling between bytes of one command makes the slave treat each byte as a new command.

I measure CS fall to first SCLK edge, last SCLK edge to CS rise, and any CS high gap inside one command. A common bug is a driver that deasserts CS in the transfer-complete interrupt and reasserts it in the next interrupt, inserting microseconds mid-command. The analyzer shows that gap plainly. Hardware CS with a programmed setup delay is the right choice for a single slave on a dedicated pin, because the timing is deterministic. GPIO CS is acceptable when the pin is shared or the peripheral lacks hardware CS, but only if the GPIO is set before the clock starts and held until the last edge completes, with interrupts masked or the timing verified under worst-case interrupt load. If GPIO CS timing varies with interrupt load and the corruption does too, that correlation is the diagnosis.

Sequence

Capture with a fixed pattern and CRC, decode both directions, classify as shift, extra edge, truncation, or threshold-dependent, then change one variable at a time. Halve the clock. Add 100 ns of CS setup. Swap CPHA. Each change either removes the corruption or moves the signature, and that movement shows which constraint was binding. If none of those changes matter, I check the DMA descriptor length and whether the buffer is still valid when the peripheral finishes, since a short DMA count truncates the frame in a way that resembles a CS fault in decoded output.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-16Walk me through I2C addressing, ACK/NACK and clock stretching, and how you recover a bus stuck low after a device resets mid-transfer?

The 90-second answer

I2C is open-drain, so both SDA and SCL are pulled high and any device can pull a line low. A transfer starts with START, SDA falling while SCL is high, and ends with STOP, SDA rising while SCL is high. The master sends a 7-bit address in the first byte, shifted left by one, with the low bit as read/write. The addressed slave pulls SDA low on the ninth clock to ACK. A NACK means no device recognised the address, or the receiver cannot accept more data. The master then issues STOP or a repeated START.

Clock stretching is the slave holding SCL low after a clock edge to make the master wait. The master must sample SCL and only continue when it goes high. A master that assumes SCL follows its own output will corrupt the transfer with a slow slave, for example a sensor finishing an ADC conversion.

If a slave resets mid-transfer it can leave SDA low because it was driving ACK, or leave SCL low because it was stretching. The bus looks dead even though the master is idle. Recovery is to clock SCL manually until the slave releases SDA, issue STOP, then reinitialise the peripheral.

Worked trace

Assume a sensor at 7-bit address 0x48, standard mode 100 kHz, master writing register 0x02 then reading two bytes. The address byte is 0x48 << 1, which is 0x90 for write and 0x91 for read.

StepSDASCLMeaning
START1 to 01Master signals start
Byte 1100100008 pulses0x90, address 0x48 plus write bit
ACK 109th pulseSlave pulled SDA low, address accepted
Byte 2000000108 pulsesRegister pointer 0x02
ACK 209th pulseSlave accepted
Repeated START1 to 01Master changes direction without STOP
Byte 3100100018 pulses0x91, address 0x48 plus read bit
ACK 309th pulseSlave ready to send
Byte 4data high byte8 pulsesSlave drives SDA
ACK 409th pulseMaster ACK, wants more
Byte 5data low byte8 pulsesSlave drives SDA
NACK 519th pulseMaster NACK, transfer complete
STOP0 to 11Master signals stop

At 100 kHz one clock is 10 µs. Nine clocks per byte is 90 µs, so the five bytes above take about 450 µs plus START and STOP overhead. At 400 kHz fast mode that falls to about 113 µs. That arithmetic matters when a 1 kHz control loop shares the bus.

10-bit addressing uses a 11110 prefix in the first byte followed by the two high address bits, then a second byte with the low eight bits. Most current sensors use 7-bit, and the 7-bit space gives 128 addresses minus the reserved ranges, so collisions happen when two parts share a fixed address pin setting.

Clock stretching in practice

A slave stretches by holding SCL low after the master releases it. The master sees SCL low and waits. Some masters have a stretch timeout, often configurable, to stop a crashed slave from hanging the bus forever. Set it above the slowest legitimate stretch. A part that stretches for 5 ms during conversion needs a timeout above 5 ms, or the master will abort a valid read. A timeout of 25 ms catches a dead slave without punishing normal operation.

Detection is simple: after driving SCL high, read back the pin. If it stays low beyond the timeout, log the address and the byte count. That distinguishes stretching from a short to ground, where SCL never rises even after recovery clocks.

Bus recovery after a mid-transfer reset

C
// Checked against STM32F4 HAL style GPIO and I2C peripheral, adapt pin names.
void i2c_bus_recover(void)
{
    gpio_set_mode(SCL_PIN, GPIO_OUTPUT_OPEN_DRAIN);
    gpio_set_mode(SDA_PIN, GPIO_INPUT);
    gpio_write(SCL_PIN, 1);
    for (int i = 0; i < 9 && gpio_read(SDA_PIN) == 0; i++) {
        gpio_write(SCL_PIN, 0);
        delay_us(5);
        gpio_write(SCL_PIN, 1);
        delay_us(5);
    }
    // STOP: SDA low while SCL high, then SDA high.
    gpio_set_mode(SDA_PIN, GPIO_OUTPUT_OPEN_DRAIN);
    gpio_write(SDA_PIN, 0);
    delay_us(5);
    gpio_write(SDA_PIN, 1);
    delay_us(5);
    i2c_peripheral_reinit(100000); // 100 kHz, re-enable ACK handling
}

Nine clocks flush a slave that is mid-byte, because each clock advances its state machine until it reaches a point where it releases SDA. If SDA is still low after nine clocks, the slave is holding it for another reason. Options then are a reset pulse to that slave if it has one, or a power cycle through a load switch. Reinitialising the master peripheral alone will not free a slave that still drives SDA.

Yes No Detect SDA low while bus idle Reconfigure SCL as GPIO, SDA as input Clock SCL up to 9 times SDA high? Issue STOP Reset or power-cycle slave Reinitialise I2C peripheral Probe address, log recovery count

Failure modes I check on the scope or logic analyser: missing pull-ups leave both lines floating and START never completes, a 10-bit slave ACKing a 7-bit probe, and a master that issues STOP while a slave is still stretching, which the slave may interpret as a new START. Recovery count in the log tells me whether one board in a fleet has a marginal slave or a wiring fault, rather than treating every hang as a software bug.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-17A sensor sends a 50-byte frame at 10 Hz over 9600 baud 8N1 with no flow control and you see occasional overrun errors: how do you check capacity, explain framing and parity, and size the receive buffer for a 20 ms task delay?

The 90-second answer

First I check whether the wire can carry the load. At 9600 baud with 8N1, each byte costs 10 wire bits: one start bit, eight data bits and one stop bit. The ceiling is therefore 9600 / 10 = 960 bytes per second. The sensor sends 50 bytes at 10 Hz, which is 500 bytes per second, about 52 percent of the ceiling. Capacity is not the problem. The overruns come from the receive side being drained too slowly, so I size the buffer from the worst drain delay and then decide whether flow control is needed at all.

Framing and parity in this setup

The receiver resynchronises on the start bit and samples each bit near its centre, typically with 16x oversampling. It then checks the stop bit. If the stop bit reads as 0, the hardware flags a framing error. That usually means the two baud rates disagree, a clock has drifted, or the peer reset mid-frame. Parity is an extra bit after the data bits, set to make the count of 1 bits even or odd. It catches a single-bit error and misses a double-bit error. With 8N1 there is no parity bit, so a parity error cannot occur. I would keep 8N1 here and put a CRC or checksum in the sensor frame instead, because parity costs 10 percent of throughput for weak protection.

Why an overrun happens

The UART hardware has a small receive register or FIFO, often 1 to 16 bytes. If the next byte arrives before software has read the previous one, the hardware sets the overrun flag and the new byte is lost. On many STM32 parts, reception also stops until software clears the flag by reading the status register and then the data register in the order given in the reference manual. The sensor rate is steady, so an occasional overrun points at a moment when the ISR or task was delayed, for example by a flash write or a higher priority interrupt, rather than at a sustained overload.

SymptomLikely causeCheck
Overrun flag set, framing error clearReceive register not read in timeCount overruns, measure worst-case interrupt and task latency
Framing error setBaud mismatch or clock driftMeasure the actual baud on a scope, compare both clock sources
Parity error setWrong parity mode on one end, or noiseConfirm both ends agree, inspect signal levels
No errors, but frames fail CRCData lost earlier, or line noiseLog error counters alongside CRC failures

Sizing the buffer for a 20 ms delay

The buffer must hold everything that arrives while the consumer is not running:

bytes_during_delay = throughput * worst_case_delay
                   = 960 * 0.020
                   = 19.2 bytes

Add one full 50-byte frame, because a frame can start just before the delay begins, and the requirement is about 70 bytes. I would allocate 256 bytes. That leaves margin for a second frame and keeps the size a power of two for cheap masking. If the delay grew to 200 ms, the same arithmetic gives 192 bytes plus a frame, so 256 bytes would be marginal and I would move to 512 bytes.

A minimal interrupt-driven ring buffer:

C
#define RX_SIZE 256u
static uint8_t rx_buf[RX_SIZE];
static volatile uint16_t rx_head, rx_tail;
volatile uint32_t ore_count;

void USART_IRQHandler(void)
{
    uint32_t sr = USART1->SR;
    if (sr & USART_SR_ORE) {
        ore_count++;
        (void)USART1->DR; /* clears ORE on STM32 families, order per reference manual */
        return;
    }
    if (sr & USART_SR_RXNE) {
        uint16_t next = (uint16_t)((rx_head + 1u) & (RX_SIZE - 1u));
        if (next != rx_tail) {
            rx_buf[rx_head] = (uint8_t)USART1->DR;
            rx_head = next;
        } else {
            (void)USART1->DR; /* buffer full, drop and count in production code */
        }
    }
}

The consumer task reads from rx_tail and I expose ore_count on a debug channel. If the count stays at zero during a soak test at full sensor rate, the buffer and latency budget are adequate.

Flow control, only if the buffer cannot cover the delay

MethodCostFit for this link
None, sized bufferRAM only, data lost if delay exceeds bufferBest fit here, since 256 bytes covers 20 ms with margin
RTS/CTS hardwareTwo pins, correct polarity setupUse if the task delay grows or bursts get larger
XON/XOFF softwarePayload bytes 0x11 and 0x13 need escaping, resume latencyPoor fit for binary sensor frames

With no flow control, the peer keeps sending during the 20 ms delay and the buffer absorbs it. That works because the average load is only half the wire capacity, so the buffer drains again before the next frame. If the sensor sent at 900 bytes per second, close to the ceiling, the buffer would never recover and RTS/CTS would become the right answer.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-18Which of SPI, I2C and UART lets several peripherals share just two wires, and how does the controller tell them apart?

The 90-second answer

I2C. It is the one of the three built for many peripherals on two shared wires, SDA for data and SCL for clock. Every frame starts with a 7-bit address that names the target device. Only the device whose address matches responds and pulls SDA low for the ACK bit. The others ignore the frame.

SPI also shares clock and data lines, but it separates devices with a separate chip select line per peripheral. UART is point to point, with a TX and RX pair and no address at all. If the design goal is few pins for several slow on-board devices, that points to I2C in one step.

BusShared wiresHow a device is selected
I2CSDA, SCL7-bit address in the frame, ACK from the matching device
SPISCLK, MOSI, MISOOne CS line per device, asserted by the controller
UARTTX, RXNo selection, one device at each end

A typical write looks like this in C. The address is shifted left by one because the I2C frame carries a read or write bit after the 7-bit address, and some libraries expect that 8-bit form.

C
/* STM32 HAL, 7-bit device address 0x48 */
uint8_t data[2] = {0x01, 0x5A}; /* register 0x01, value 0x5A */
HAL_StatusTypeDef st = HAL_I2C_Master_Transmit(&hi2c1, 0x48 << 1, data, 2, 100);
if (st != HAL_OK) {
    /* No ACK means the address is wrong, the device is absent, or the bus is stuck */
}

On the wire the controller sends a start condition, the address plus write bit, then waits for ACK. It sends the register byte, waits for ACK again, sends the value, waits for ACK, then sends a stop condition. A read reverses the direction after the register byte, usually with a repeated start so the bus is not released between the two parts.

Two practical limits follow from the same design. The address must be unique on the bus, so two identical parts with fixed addresses cannot both sit on one I2C bus without an address pin change or a multiplexer. Pull-up resistors on SDA and SCL are required, commonly 4.7 kΩ at 3.3 V, and they set the rise time that caps speed and bus length. That is why I2C suits sensors and configuration chips at 100 kHz or 400 kHz, while a display or flash part that needs megabytes per second usually ends up on SPI.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-19Walk me through what happens from reset vector to jumping to the application, including vector table relocation and who owns clock initialization?

The 90-second answer

On a Cortex-M part such as the STM32F407, reset does not run code from address zero. The core reads the first two words at the boot address, loads the initial stack pointer from word 0 and the reset handler address from word 1, then starts executing the reset handler. Everything after that is firmware convention, and the split between bootloader and application is where most field failures hide.

The ROM bootloader, if it runs, has already done the minimum to talk to a host or load firmware. A custom bootloader then copies or verifies the application image, relocates the vector table, hands over a clean CPU state, and jumps. The application startup code, usually Reset_Handler plus SystemInit() from CMSIS, copies .data from flash to RAM, zeroes .bss, configures clocks and flash wait states, enables the FPU if present, and calls main().

StageWhat runsMust be true on exit
ResetCore reads SP and reset handler from vector table at boot addressSP is valid RAM, reset handler is in flash
Early startupReset_Handler in bootloader or applicationInterrupts disabled, stack set, .data copied, .bss zeroed
Clock setupSystemInit() or bootloader clock codeFlash wait states match core clock, PLL locked, bus dividers sane
Vector relocationWrite SCB->VTOR to application tableEvery IRQ the application enables vectors into application handlers
HandoverBootloader disables IRQs, sets MSP, jumpsNo pending IRQ, no bootloader SysTick, no shared peripheral state
Application startupApplication Reset_Handler and SystemInit()Clocks rechecked, VTOR correct, main() reached

Vector table relocation

SCB->VTOR points the core at the active vector table. After reset it points at the boot table, usually flash base 0x08000000. If the bootloader stays resident and the application lives at, say, 0x08010000, the application must set VTOR to its own table before enabling any interrupt it owns. The table must be aligned to its size rounded up to a power of two. The STM32F407 has 16 core exceptions and 82 maskable IRQs, so 98 entries at 4 bytes each is 392 bytes, and 512-byte alignment is the safe choice on that part. Misaligning VTOR truncates the table and later vectors alias to the wrong handlers.

The trap is enabling interrupts in the bootloader, for example a UART or SysTick used for a timeout, then jumping without clearing them. The application sets VTOR, but a pending IRQ fires first and vectors into the bootloader table, or into a handler the application has not installed yet. The fix is boring and strict: __disable_irq(), clear pending IRQs with NVIC->ICPR, stop SysTick, then set VTOR and MSP and jump.

C
/* Bootloader handover, Cortex-M4, application at 0x08010000 */
#define APP_BASE 0x08010000u

typedef void (*app_entry_t)(void);

void jump_to_application(void)
{
    uint32_t app_sp = *(volatile uint32_t *)APP_BASE;
    uint32_t app_reset = *(volatile uint32_t *)(APP_BASE + 4);
    app_entry_t app_reset_handler = (app_entry_t)app_reset;

    __disable_irq();
    SysTick->CTRL = 0;
    for (uint32_t i = 0; i < 3; i++) {
        NVIC->ICPR[i] = 0xFFFFFFFFu;
    }
    SCB->VTOR = APP_BASE;
    __set_MSP(app_sp);
    __DSB();
    __ISB();
    app_reset_handler();
}

The application reset handler then runs its own .data copy and .bss clear. A bootloader that already did that work for the application image is wasting boot time and risks double initialisation if the application does it again.

Clock initialization ownership

After reset the F407 runs from HSI at 16 MHz with flash at 0 wait states. That is safe at 16 MHz and unsafe at speed. SystemInit() on this family typically configures the PLL to 168 MHz, sets AHB at 168 MHz, APB1 at 42 MHz and APB2 at 84 MHz, and sets 5 flash wait states for 2.7 to 3.6 V operation. Order matters: raise wait states before raising the clock, or the core fetches garbage from flash during the switch.

Who owns this when a bootloader exists is a design decision, and it has to be written down. Three workable splits:

  1. Bootloader owns clocks end to end. It configures 168 MHz, leaves the PLL running, and the application SystemInit() detects that and skips reconfiguration. Fast handover, but the application cannot be flashed standalone and run correctly, which breaks factory test and recovery.
  2. Application owns clocks. The bootloader runs at HSI or a conservative 84 MHz, verifies the image, and jumps. The application configures 168 MHz itself. Slower boot, cleaner ownership, and the same image works with or without the bootloader.
  3. Split by contract. The bootloader passes a clock configuration block in a fixed RAM address or a reserved register, and the application applies it. Flexible, and a version mismatch between bootloader and application silently produces the wrong UART baud rate.

I default to option 2 for products that ship a bootloader for field updates. The bootloader needs only enough clock to read flash and run a CRC or signature check. The application owns the full tree, so a standalone application image behaves identically.

Two failure modes show up in the field. First, the bootloader enables the FPU or leaves CP10 and CP11 in SCB->CPACR enabled, the application assumes a cold reset state, and floating point code faults or behaves differently after an update than after a power cycle. Second, the bootloader leaves a peripheral clock enabled, for example DMA or a timer, and the application reconfigures that peripheral while a DMA transfer is still in flight. Clearing peripheral clocks and DMA channels in the handover path, before the jump, removes both.

Reset: read SP and reset handler Bootloader startup: copy data, zero bss Verify application image Disable IRQs, stop SysTick, clear pending Set VTOR to application table, set MSP Jump to application reset handler Application SystemInit: clocks and flash wait states main

If an interviewer pushes on timing, the honest answer is that the jump itself costs microseconds. The expensive parts are image verification and clock reconfiguration. PLL lock on this part is at most about 200 µs, so it is not the bottleneck. Verification can be: a software CRC32 at roughly 10 cycles per byte (hypothetical figure for a table-driven implementation) over a 512 KB image is about 5.2 million cycles, or about 330 ms at 16 MHz, which is why the F407 hardware CRC unit exists and why a signature check over the full image needs its own boot time budget rather than being treated as free.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-20Your device has two flash slots for A/B updates: how does the bootloader use CRC and signature checks on the inactive slot to decide whether to boot it or roll back after a power loss during the write?

The 90-second answer

The running image stays in slot A and the update goes to slot B. Nothing in slot B is trusted until the bootloader has checked it in full. Only after those checks pass does the bootloader flip a boot flag to B. If power fails before that flip, the flag still points at A, so the device boots the old firmware and the partial update is ignored.

Assume 4 KiB NOR erase sectors and an image header at the start of each slot. The header stores the payload length, a CRC32 of the payload, and a signature over the header and payload. The updater erases B, writes the payload, writes the header last, then resets. Writing the header last matters: a torn payload has no valid header, so the bootloader rejects B without needing to guess where the write stopped.

CRC32 and the signature do different jobs. CRC32 is fast and catches torn writes, bit flips and a truncated transfer. It is not security, since anyone can recompute it. The signature, ECDSA P-256 checked against a public key in the bootloader, catches an image that was not produced by your signing key. A candidate who uses only one of them has a gap: CRC alone accepts a tampered image, signature alone still needs a length and integrity check before you spend time verifying a corrupt payload.

C
// Cortex-M4, GCC 12, bootloader code
typedef struct __attribute__((packed)) {
    uint32_t magic;          // 0x46574D47
    uint32_t image_len;      // payload bytes after this header
    uint32_t payload_crc32;
    uint8_t  sig[64];        // ECDSA P-256 r||s
} image_header_t;

bool slot_valid(uint32_t base) {
    const image_header_t *h = (const image_header_t *)base;
    if (h->magic != 0x46574D47u) return false;
    if (h->image_len == 0 || h->image_len > SLOT_SIZE - sizeof(*h)) return false;
    const uint8_t *payload = (const uint8_t *)(base + sizeof(*h));
    if (crc32(payload, h->image_len) != h->payload_crc32) return false;
    return ecdsa_verify(BOOT_PUBKEY, (const uint8_t *)base,
                        sizeof(*h) + h->image_len);
}

Boot decision and rollback

The bootloader keeps two small metadata records, each with its own CRC, and uses the newest valid one. A record names the confirmed slot and, during an update, the pending slot plus a trial counter. The new image must confirm itself, for example by reaching main(), initialising its clocks and setting a confirm flag, within 3 trial boots. If it crashes or loses power before confirming, the counter runs out and the bootloader clears the pending slot and boots the confirmed one.

No Yes No Yes Yes No, trials left No, trials exhausted Reset: read newest valid metadata Pending slot present? Boot confirmed slot slot_valid pending? Boot pending, decrement trials App confirmed? Pending becomes confirmed
Power loss pointWhat the bootloader seesResult
Erasing or writing BNo valid header in B, flag still on ABoots A
Payload complete, header tornCRC or signature fails in BBoots A, B discarded
Header valid, flag not yet flippedB verifies, but metadata still names ABoots A, update retried
First boot of B, before confirmPending set, trials remainingBoots B, counts a trial
B crashes on all 3 trialsTrials exhaustedBoots A, B cleared
B confirmedMetadata names B as confirmedBoots B, A is fallback

Two failure modes come up in interviews. First, a signed image that still crashes, such as a clock change that faults on one board revision. Signature checks pass, so without trial boots and confirmation the device would boot a broken image forever. Second, erasing the wrong slot. NOR flash cannot be rewritten byte by byte, so the updater must erase a full 4 KiB sector before writing it, and it must never erase the slot it is running from. Erase can take 100 ms to 1 s per sector, so the update protocol and watchdog have to tolerate a multi-second erase of a 256 KiB image.

A/B costs flash, two copies of the image, in exchange for rollback without a recovery tool. On a small part where that cost is too high, a single slot plus a recovery bootloader that re-downloads over UART is the alternative, but then a power loss mid-write leaves the device unbootable until someone connects a cable.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-21Why can't firmware just overwrite a byte in NOR or NAND flash like RAM, and how do erase granularity, page programming and wear leveling shape an in-place update design?

The 90-second answer

Flash is not RAM because a write can only clear bits, never set them. A cell ships erased as all 1s. Programming applies voltage to trap charge and turns 1s to 0s. Turning a 0 back to 1 needs an erase, which resets a whole sector or block at once. So an update is never a byte overwrite. It is read the unit, erase the unit, program the new image, and survive power loss in the middle.

NOR and NAND make that trade differently. NOR gives fast random reads and execute-in-place, which is why boot code lives there, but erase units are large and programming is slow. NAND gives dense, cheap storage with page programming, but reads are sequential by page, it needs ECC and bad-block management, and endurance depends strongly on cell type.

PropertyNORNAND
ReadRandom, XIP capable, about 70 nsPage based, 2 to 16 KB pages, needs buffer
ProgramByte or word, 1 to 0 onlyPage only, 1 to 0 only
Erase unitSector, typically 64 to 128 KBBlock, typically 64 to 256 pages, 128 KB to 4 MB
Erase timeSector typically 100 to 200 ms, up to about 400 msBlock typically 2 to 10 ms
EnduranceAbout 100,000 cyclesSLC about 100,000, MLC about 3,000 to 10,000, TLC about 1,000 to 3,000
Extra needsLittleECC, bad block table, FTL or raw management

NOR endurance is comparable to SLC NAND at about 100,000 cycles. It is higher than MLC or TLC NAND, which is the comparison that matters for cheap storage parts.

Why in-place update hurts

Suppose a 64 KB NOR sector holds config at offset 0 and a 4 KB log at offset 60 KB. Changing one byte in the log forces the driver to copy the sector to RAM, erase it, and reprogram 64 KB. During that erase the sector reads as erased, XIP from it faults, and a reset leaves neither old nor new data. On NAND the unit is a block, so the same problem is larger, and programming a page that was already programmed without an erase is rejected or corrupts data.

Wear makes direct rewriting worse. Take a hypothetical TLC NAND part rated at 3,000 cycles and a firmware that rewrites the same 4 KB page every minute for a settings log. That is 3,000 writes in 3,000 minutes, which is 50 hours or about 2.1 days, so that page fails long before the rest of the chip wears out. Wear leveling spreads writes across a pool of pages. If the FTL rotates the log across 1,024 pages (4 MB at 4 KB per page), each page gets 525,600 / 1,024 = about 513 writes per year, and 3,000 / 513 is about 5.8 years. That is the point of the mapping layer: it trades a fixed page for a rotating set.

C
/* Copy-on-write update for a NOR config sector, checked against Cortex-M / C11 */
int config_update(const uint8_t *new_img, size_t len) {
    uint32_t crc = crc32(new_img, len);
    flash_erase(SECTOR_B);                 /* B is the inactive bank */
    flash_program(SECTOR_B, new_img, len); /* 1 -> 0 only */
    flash_program(SECTOR_B + len, &crc, 4);
    flash_program(SECTOR_B + len + 4, COMMIT, 4); /* commit last */
    return (read_crc(SECTOR_B) == crc) ? 0 : -1;
}

The commit word is programmed last. On boot, firmware checks bank A, then bank B, and picks the newest bank whose CRC and commit marker both validate. A power cut during erase or program leaves the old bank intact.

Yes No Yes No Boot: validate bank A Valid? Run from A Validate bank B Valid? Recovery image Erase inactive bank Program new image + CRC Program commit marker Reset and boot from new bank

Failure modes to name in the interview

Program disturb and read disturb on NAND: reading or programming neighbours can flip marginal cells, which is why ECC corrects single-bit errors and the FTL retires pages that exceed the correction budget. Bad blocks: NAND ships with factory bad blocks and grows more with wear, so the driver must skip them on erase and keep a spare pool, typically 2 percent of blocks. Interrupted erase on NOR: the sector can return indeterminate data, so never erase the bank you are executing from and never trust a sector without a CRC. Watchdog interaction: a 200 ms NOR sector erase will trip a 100 ms watchdog unless the update task feeds it from a higher priority context or the erase is chunked with the watchdog serviced between chunks.

For a small config store on NOR, dual sectors with CRC are enough. For a filesystem or log on NAND, you need a log-structured layer or FTL that appends pages, remaps logical to physical addresses, garbage collects full blocks, and levels wear. That layer is the cost of turning erase-before-write flash into something that looks like a writable disk.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-22How do you calculate average current, average power and battery life for a sensor that sleeps at 2 µA and draws 12 mA for 50 ms every 10 seconds?

The 90-second answer

Time-weight the currents. If the sensor is active for t_active in a period T and asleep for the rest, average current is the charge per period divided by the period:

I_avg = (I_active * t_active + I_sleep * (T - t_active)) / T

Average power is P_avg = V * I_avg, using the supply voltage during operation. Battery life in hours is capacity_mAh / I_avg_mA. That is the whole method. The traps are using peak current, forgetting the sleep term, and quoting the ideal life without derating.

Worked example

Assume a 3.0 V rail, I_sleep = 2 µA, I_active = 12 mA, t_active = 50 ms, T = 10 s. Duty cycle is 50 ms / 10 s = 0.5%.

QuantityCalculationResult
Active charge per cycle12 mA * 0.050 s0.60 mC
Sleep charge per cycle0.002 mA * 9.95 s0.0199 mC
Total charge per cycle0.60 + 0.01990.6199 mC
Average current0.6199 mC / 10 s62 µA
Average power3.0 V * 62 µA186 µW
Ideal life, 2000 mAh cell2000 mAh / 0.062 mA32,258 h, about 3.7 years

Note the split: sleep contributes only 2 µA of the 62 µA average. Cutting active time or active current matters far more than shaving sleep current once duty cycle is this low. If wake time fell to 5 ms, average current would drop to about 8 µA and ideal life would rise to roughly 28 years, at which point self-discharge and shelf life, not the load, set the real limit.

C
// Currents in uA, times in ms, capacity in mAh. Returns uA.
float avg_current_ua(float i_sleep_ua, float i_active_ua,
                    float t_active_ms, float period_ms)
{
    float duty = t_active_ms / period_ms;
    return i_sleep_ua * (1.0f - duty) + i_active_ua * duty;
}

// Example: avg_current_ua(2.0f, 12000.0f, 50.0f, 10000.0f) -> 62 uA
// Battery life in hours: 2000.0f / (62.0f / 1000.0f) -> 32258 h

What to check before quoting a life

Real life is shorter than the ideal figure for three concrete reasons. First, usable capacity: a lithium cell delivers less at low temperature and near end of discharge, so derate to 70 to 85% of nominal capacity for a conservative estimate. Second, self-discharge: at 1 to 2% per year, a cell loses capacity even with no load, which caps any calculation above about 10 years. Third, the sleep current you use must be the measured system sleep current, including regulator quiescent current, RTC, and leakage at temperature, not just the MCU datasheet stop current. A regulator drawing 5 µA quiescent would more than triple the sleep term here.

Also confirm t_active includes everything that keeps the rail up: sensor warm-up, ADC settling, I2C or SPI transfer, radio transmit if present, and the wake-up and shutdown overhead. A 20 ms radio burst at 30 mA inside that 50 ms window changes the charge per cycle materially, so measure with a current profiler or a shunt and oscilloscope over several cycles rather than trusting a single datasheet number. If the period is not fixed, replace T with total elapsed time and sum charge over the same window.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-23Your battery sensor must wake on a GPIO or RTC every 10 s, keep RAM state, and answer within 5 ms: how do you choose Sleep, Stop or Standby and prove the wake budget?

The 90-second answer

Pick the shallowest mode that meets the current budget and still wakes in time. Sleep keeps the clocks and peripheral state, so wake is a few microseconds, but you pay for every clock you leave on. Stop drops the core clocks and puts the regulator in low power, SRAM and RTC stay alive, and wake costs tens to hundreds of microseconds for the regulator and clock tree to come back. Standby (called Deep Sleep on some vendors) powers SRAM down except the backup domain, so wake is a reset, typically milliseconds, and you must rebuild peripheral state from flash. Names differ by vendor, so I map the mode to three facts from the datasheet: what is retained, which wake sources stay armed, and the wake time from the power-down state, not from WFI alone.

For a sensor that wakes every 10 s, keeps RAM state, and must answer within 5 ms, I would start in Stop2 on an STM32L4 class part, with RTC and one GPIO EXTI as wake sources. If the 5 ms budget includes sensor settling, that leaves room. Standby would only win if Stop current missed the battery target by a factor the product cannot accept, and then I would accept the reset cost and store state in backup registers or flash.

Mode (STM32L4 example)RetainedWake latency, typicalCurrent, typicalWake sources that stay armed
SleepSRAM, peripheral config, clocks gated by software1 to 5 us after WFI100 us to mA range, depends on clocks left onAny interrupt, including UART, I2C, timers
Stop2SRAM, RTC, GPIO state; most peripheral clocks off, flash in low power30 to 100 us including regulator ramp1 to 5 uA with RTC onEXTI GPIO, RTC, some UART/I2C address match, comparator
StandbyBackup SRAM and RTC only, main SRAM lost1 to 3 ms, reset sequence plus clock init0.3 to 1 uAWakeup pin, RTC, IWDG, NRST

Figures above are datasheet class values for that family at 25 C, 3.0 V, and they move with voltage and temperature. I recheck them against the exact part and revision before committing a battery claim.

No Yes Yes No No Yes Wake deadline and current budget RAM state needed? Standby Wake in under 100 us? Sleep Stop Stop current meets budget?

Choosing and entering the mode

The decision is arithmetic before it is architecture. Take a 2000 mAh cell, a 50 ms active burst at 12 mA every 10 s, and Stop at 3 uA. Average current is 3 uA plus 12 mA times 0.005, which is 63 uA. That gives about 3.6 years before self discharge and regulator quiescent current eat into it. If Standby at 0.5 uA saves 2.5 uA of that 63 uA, it buys roughly 4 percent of life and costs a full reinit on every wake. That trade rarely pays unless the active burst is far shorter.

C
/* STM32 HAL, checked against STM32L4 HAL 1.3.x */
void enter_stop_for_10s(void)
{
    /* Arm wake sources before sleeping, then clear stale flags. */
    __HAL_RTC_CLEAR_FLAG(&hrtc, RTC_FLAG_ALRAF);
    HAL_GPIO_WritePin(WAKE_GPIO_Port, WAKE_Pin, GPIO_PIN_RESET);
    __HAL_GPIO_EXTI_CLEAR_FLAG(WAKE_Pin);

    /* Stop2: SRAM retained, wake on RTC alarm or EXTI. */
    HAL_PWR_EnterSTOPMode(PWR_LOWPOWERMODE_STOP2, PWR_STOPENTRY_WFI);

    /* On wake, the clock tree is restored by the HAL wakeup path.
       Check which source fired before touching the sensor. */
    if (__HAL_RTC_GET_FLAG(&hrtc, RTC_FLAG_ALRAF)) {
        __HAL_RTC_CLEAR_FLAG(&hrtc, RTC_FLAG_ALRAF);
        schedule_sensor_cycle();
    } else if (__HAL_GPIO_EXTI_GET_FLAG(WAKE_Pin)) {
        __HAL_GPIO_EXTI_CLEAR_FLAG(WAKE_Pin);
        handle_external_event();
    }
}

Two details decide whether this works in the field. First, wake sources must be enabled in the low power domain, not just in the NVIC. A GPIO that wakes from Stop needs its EXTI line and pull configured for the sleep state, and the pin must not be driven by a peripheral clock that Stop gates. Second, I measure wake latency on a scope: toggle a GPIO as the last instruction before WFI and again on the first instruction after wake, then add sensor settling time. The datasheet wake time covers regulator and PLL recovery, and my measurement catches the extra cost of restoring the clock tree and any flash wake.

Failure modes I check

A UART or I2C wake source that works in Sleep often fails in Stop because the peripheral clock is off and the receiver needs a start bit or address match to clock the domain back on. I test each wake source alone, with the debugger detached, because a debugger can hold clocks or change regulator mode. GPIO leakage is the other common miss: a pin left as push-pull output driving an LED, or an analog pin with its buffer on, can add tens of microamps and erase the Stop advantage. I audit that with a current analyser per rail, then by forcing pins to analog input one group at a time.

If the product later needs to keep a BLE or sensor FIFO alive across sleep, I move that peripheral to a low power clock domain or accept Sleep for the connected interval and Stop only between events. The mode choice then becomes per interval, not per product, and the firmware records the wake cause in retained RAM so the next cycle can prove which source fired and how long wake actually took.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-24Your PLL never sets its lock bit and the board stays on the fallback clock: how do you debug the clock tree from oscillator to status registers?

The 90-second answer

A PLL that never sets its lock bit is almost never a PLL problem first. I check, in order: is the reference oscillator actually running, is the PLL configuration inside the datasheet ranges, and did I switch the system clock only after the status bits confirm the new source. If any of those fail, I stay on the fallback clock and log the status registers instead of hanging in a wait loop.

Assume an STM32F4 style tree for concreteness: HSE 8 MHz crystal, PLLM 8, PLLN 336, PLLP 2, giving 168 MHz SYSCLK. The arithmetic matters because most lock failures I have seen were a divider pushing the VCO input or VCO output outside its allowed window, not a broken crystal.

CheckRegister / signalWhat good looks likeWhat it tells you if bad
Reference runningRCC_CR.HSERDY, scope on OSC_INHSERDY set within HSE startup time, clean sine/square on pinCrystal not oscillating, wrong load caps, bypass mode mismatch, or HSEON never set
PLL enabledRCC_CR.PLLSRC, RCC_CR.PLLONBoth set before pollingPLL fed from HSI when the math assumed HSE, or PLL never turned on
PLL lockedRCC_CR.PLLRDYSet within the datasheet lock time, typically under 1 msVCO input or output out of range, PLL supply not ready, or wrong PLLN/PLLM/PLLP
Actual SYSCLK sourceRCC_CFGR.SWS[1:0]Matches the source you requested in SW[1:0]You requested PLL but the chip is still on HSI, so peripherals run at 16 MHz while flash wait states assume 168 MHz
Clock securityRCC_CIR.HSECSSF, RCC_CR.CSSONNo CSS flagHSE failed after startup and the chip already fell back, which explains a sudden slowdown

How I bring it up in code

I never poll forever. I poll with a timeout from the DWT cycle counter, check each stage separately, and only switch SYSCLK after PLLRDY. If lock times out, I leave SYSCLK on HSI, set flash wait states for 16 MHz, and record the RCC registers to RAM for later readout over SWD or UART at the fallback baud rate.

C
/* STM32F4, checked against RM0368. SYSCLK target 168 MHz from 8 MHz HSE. */
static int pll_lock_with_timeout(uint32_t timeout_cycles)
{
    uint32_t start = DWT->CYCCNT;
    RCC->CR |= RCC_CR_HSEON;
    while (!(RCC->CR & RCC_CR_HSERDY)) {
        if ((DWT->CYCCNT - start) > timeout_cycles) return -1; /* HSE dead */
    }
    RCC->PLLCFGR = (8U << RCC_PLLCFGR_PLLM_Pos) |
                   (336U << RCC_PLLCFGR_PLLN_Pos) |
                   (0U << RCC_PLLCFGR_PLLP_Pos); /* PLLP = 2 */
    RCC->CR |= RCC_CR_PLLON;
    start = DWT->CYCCNT;
    while (!(RCC->CR & RCC_CR_PLLRDY)) {
        if ((DWT->CYCCNT - start) > timeout_cycles) return -2; /* PLL no lock */
    }
    return 0;
}

The separate return codes are the point. Return -1 sends me to the scope and the crystal circuit. Return -2 sends me to the PLL math and the PLL power supply. A single generic timeout merges two different hardware causes into one useless log line.

Fallback and the switch

no yes no yes Reset, SYSCLK = HSI 16 MHz HSE ready? Stay on HSI, log RCC_CR, halt or safe mode Configure PLLM/N/P, set PLLON PLLRDY within timeout? Set flash wait states, then SW = PLL, verify SWS

Order in that last step is a real failure mode. If you switch to 168 MHz before adding the required flash wait states, the first fetch from flash can return garbage and the core faults or appears to hang, which looks exactly like a PLL problem. I set wait states for the target frequency first, switch, then confirm SWS reads back PLL. If SWS still reads HSI, the switch did not happen and every baud rate and timer period downstream is wrong by a factor of about ten.

Two more checks before I blame the PLL chip. First, the PLL has its own supply and reference requirements in the datasheet, including VCO input frequency range (1 to 2 MHz on F4, so PLLM must divide 8 MHz down to 1 MHz) and VCO output range (192 to 432 MHz, so 336 MHz is legal). A PLLN of 500 would lock on some samples and never on others. Second, if the board uses an external oscillator or a clock buffer instead of a crystal, HSE bypass mode must match what is actually soldered. A crystal fitted where the firmware expects bypass, or the reverse, gives a dead reference and a PLL that can never lock.

If CSS is enabled and HSE dies at runtime, the chip switches to HSI automatically and sets HSECSSF. That is a feature, but it silently changes UART baud and I2C timing. My ISR for that event logs the flag and re-derives peripheral clocks from HSI rather than assuming 168 MHz is still true.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-25Walk me through using OpenOCD and GDB over SWD to halt a Cortex-M core that never runs, set breakpoints, and inspect registers to find why?

The 90-second answer

I would attach with OpenOCD as a GDB server over SWD, halt the core, and read PC, SP, and the fault registers before letting it run. A core that never runs usually fails in one of three places: it never leaves reset, it fetches a bad vector, or it faults in Reset_Handler. That first dump separates the cases.

TCL
# openocd.cfg for an STM32F4, OpenOCD 0.12
source [find interface/stlink.cfg]
source [find target/stm32f4x.cfg]
adapter speed 1000
GDB
target extended-remote localhost:3333
monitor reset halt
info registers
x/8i $pc

I start at 1000 kHz, not 4000 kHz, because a board with a long SWD lead or a slow clock often fails to connect at full speed. If the firmware drops into STOP or STANDB within milliseconds, I connect under reset so OpenOCD holds NRST while it attaches, then halt. Without that, the core can be asleep before the debugger sees it.

Reading the halt

What I seeLikely causeNext check
PC is 0x00000000 or 0xFFFFFFFFVector table not fetched, VTOR wrong, or flash erasedRead address 0, read VTOR at 0xE000ED08, check BOOT pins
PC in Reset_Handler, SP saneStartup is running but hangingStep through startup, check clock enable and .data/.bss init
PC in HardFault handlerEarly faultRead CFSR, HFSR, BFAR
PC does not move on continueCore in WFI or clock stoppedCheck SCR, clock tree, try monitor step

For the fault case I read the Cortex-M fault registers directly:

GDB
x/wx 0xE000ED28  # CFSR
x/wx 0xE000ED2C  # HFSR
x/wx 0xE000ED38  # BFAR, valid only if CFSR bit 15 (BFARVALID) is set
x/wx 0xE000ED34  # MMFAR
info registers sp lr pc xpsr

A BFAR of 0x00000000 with BFARVALID set points at a null or unmapped access in startup. HFSR.FORCED with CFSR.PRECISERR points at a precise bus error, for example touching a peripheral whose clock is still off. I also check xPSR bit 24, the Thumb bit. If it is clear, the next exception return will fault, which can look like a hang in the first interrupt.

Breakpoints

Cortex-M hardware breakpoints use the Flash Patch Block, typically 4 to 8 comparators on STM32F4. GDB break *0x08001234 will use one if OpenOCD reports support. A software breakpoint overwrites the instruction in memory with a BKPT encoding (0xBExx). That fails when code runs from RAM, flash is locked, or the target is read-only, so I prefer hardware breakpoints and check info breakpoints to see how many are left. If I run out, I put one breakpoint in the fault handler and print registers there instead of filling every comparator.

Tool choice and limits

OpenOCD is my default because it is open, scriptable, and supports most boards I meet. Its cost is slower flash programming and fiddly config on some targets. A J-Link GDB Server is faster, has better real-time transfer, and is worth it if I debug the same target daily, but it ties me to one vendor probe. pyOCD is convenient in Python and CMSIS-Pack based, yet support for less common parts lags OpenOCD. None of these help if readout protection is on, SWD is disabled in option bytes, or the chip has no power. In those cases I fix wiring, BOOT pins, and rails first, and for instruction trace I would move to a probe with ETM support rather than stay with SWD halt and step.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-26Which tool decodes SPI, I2C and UART traffic for you, and which tool shows ripple and droop on a power rail?

The 90-second answer

A logic analyzer decodes SPI, I2C and UART. An oscilloscope shows ripple and droop on a power rail.

A logic analyzer records each wire as high or low and its software turns the pattern into bytes, addresses and commands. An oscilloscope records voltage against time, so it shows how far a rail moves from its nominal value. A rail that sags from 3.3 V to 2.9 V still reads as high on a logic analyzer, so that tool cannot answer a power question at all.

How each tool decides

A logic analyzer samples digital inputs against a threshold, often around half the supply voltage. It stores transitions rather than voltage, which lets it capture long transactions and decode them. A 16 channel unit can hold seconds of UART output at 115200 baud and label start bits, data bytes and parity errors.

An oscilloscope samples voltage. You see rise time, overshoot, ringing and ripple. The cost is fewer channels and a shorter record, plus a probe that can disturb a fast signal if its ground lead is long.

JobToolWhat it tells you
SPI flash read returns wrong dataLogic analyzerClock mode, chip select timing, bytes on the wire
I2C sensor does not acknowledgeLogic analyzerAddress, ACK or NACK, clock stretching
UART output is garbledLogic analyzerBaud rate, parity, framing errors
3.3 V rail dips when a radio transmitsOscilloscopeDroop depth, duration, ripple frequency
Reset line glitches at power upOscilloscopeGlitch amplitude and width

Worked example: power rail

Put the probe on the decoupling capacitor next to the load, use AC coupling and turn the 20 MHz bandwidth limit on. On a board I checked, the 3.3 V rail showed 35 mV peak to peak ripple at idle. When a 150 mA transmitter burst started, it drooped to 2.95 V for about 2 ms. That explained sensor resets. The fix was extra bulk capacitance near the radio, not a firmware change.

For a digital signal that decodes cleanly but the device still fails, the scope is the next step. A 50 MHz SPI clock needs a scope bandwidth of at least 250 MHz by the five times rule, and a short ground spring. Ringing on the clock edge can look like one clean transition to a logic analyzer while the peripheral sees two clocks.

Question about bytes or protocol Logic analyzer Question about voltage, ripple or droop Oscilloscope Decode SPI, I2C or UART Measure rail or signal shape

Set the logic analyzer threshold for the actual logic level. A 1.8 V device checked with a 3.3 V threshold can give a decode that looks plausible while the edges are marginal. The scope settles that in one capture.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-27Your Cortex-M device hard faults in the field: how do you read the fault registers and stacked PC/LR to tell a bus fault from a usage fault and find the faulting instruction?

The 90-second answer

Assume a Cortex-M3/M4 (ARMv7-M), MemManage, BusFault and UsageFault enabled in SCB->SHCSR, and the fault was not taken inside another fault handler. A HardFault is usually an escalation: a configurable fault fired while its handler was disabled, while another fault was already active, or the core could not stack the exception frame. So I do not start from the HardFault handler alone. I read SCB->HFSR for FORCED (bit 30), then SCB->CFSR, which is three bytes: MemManage in bits 7:0, BusFault in bits 15:8, UsageFault in bits 31:16. That tells me which fault escalated. Then I recover the stacked frame using the LR value on entry to the handler, read the stacked PC and LR, and check BFAR or MMFAR only when the corresponding VALID bit is set.

C
// Checked against ARMv7-M Architecture Reference Manual, SCB register map.
typedef struct {
    uint32_t r0, r1, r2, r3, r12, lr, pc, xpsr;
} StackedFrame;

__attribute__((naked)) void HardFault_Handler(void)
{
    __asm volatile (
        "tst lr, #4\n"          // bit 2: 0 = MSP, 1 = PSP
        "ite eq\n"
        "mrseq r0, msp\n"
        "mrsne r0, psp\n"
        "b HardFault_Handler_C\n"
    );
}

void HardFault_Handler_C(uint32_t *sp)
{
    volatile StackedFrame *f = (volatile StackedFrame *)sp;
    volatile uint32_t cfsr = SCB->CFSR;
    volatile uint32_t hfsr = SCB->HFSR;
    volatile uint32_t bfar = SCB->BFAR;
    volatile uint32_t mmfar = SCB->MMFAR;
    volatile uint32_t fault_pc = f->pc;
    volatile uint32_t fault_lr = f->lr;
    (void)cfsr; (void)hfsr; (void)bfar; (void)mmfar;
    (void)fault_pc; (void)fault_lr;
    __DSB();
    while (1) { __NOP(); } // log via SWO/semihosting in debug builds
}

The stacked PC is the address of the faulting instruction for precise faults, which is most UsageFaults and precise BusFaults. For an imprecise BusFault it points after the faulting instruction, so I treat it as an upper bound and look at recent buffered stores instead of trusting it exactly. The stacked LR is the return address in the interrupted code, useful for spotting a bad function pointer call or a return into nowhere. If UNSTKERR or STKERR is set, the frame itself may be corrupt, and the PC on the stack cannot be trusted.

Fault classCFSR byteTypical bitsWhat it meansAddress register
MemManagebits 7:0DACCVIOL 0x02, IACCVIOL 0x01MPU or memory map violationMMFAR if MMARVALID 0x80
BusFaultbits 15:8PRECISERR 0x0200, IBUSERR 0x0100, IMPRECISERR 0x0400Access to a nonexistent or protected address, or a bus error on fetchBFAR if BFARVALID 0x8000
UsageFaultbits 31:16UNDEFINSTR 0x00010000, INVSTATE 0x00020000, INVPC 0x00040000, NOCP 0x00080000, UNALIGNED 0x01000000, DIVBYZERO 0x02000000Illegal instruction, bad state, invalid PC, coprocessor not enabled, unaligned access, divide by zero when trapping enablednone

Worked trace, a null pointer write on a part with no MPU:

StepObservationReading
1HFSR = 0x40000000FORCED set, a configurable fault escalated
2CFSR = 0x00008200BusFault byte 0x82: PRECISERR (0x0200) plus BFARVALID (0x8000)
3BFAR = 0x00000000The data address that faulted
4Stacked PC = 0x0800123A, stacked LR = 0x080011F0Disassemble at 0x0800123A, expect a store through r0 = 0

That pattern is a BusFault, and the fix is in the caller that passed the null pointer. Contrast a divide by zero with SCB->CCR.DIV_0_TRP set: CFSR shows DIVBYZERO 0x02000000 in the UsageFault byte, BFAR is meaningless, and the stacked PC points at the SDIV or UDIV. An undefined opcode from executing data or a corrupted function pointer shows UNDEFINSTR or INVPC, again with no address register to consult.

Trade-offs I decide before shipping

Enabling separate MemManage, BusFault and UsageFault handlers gives precise classification at the point of failure and lets me log CFSR before escalation overwrites context. The cost is three more handlers that must themselves be fault-safe, must not use floating point or unaligned access, and must run at a priority that can preempt thread code but not a fault already in progress. Leaving them disabled and logging only in HardFault is simpler and saves vectors, but then FORCED is set and I lose the distinction between a fault that escalated because it was disabled and one that escalated because stacking failed. For a product that must diagnose field returns, I enable the three handlers and make each one capture registers and reset. For a cost-sensitive bootloader that only needs to know it faulted, logging only in HardFault is defensible.

The second decision is whether to trust the stacked PC as the faulting instruction. I trust it when PRECISERR is set or when the UsageFault byte is set, because those are precise. I do not trust it when IMPRECISERR, UNSTKERR or STKERR is set, or when BFARVALID is clear on a BusFault. In those cases the PC may be one or more instructions past the store that actually faulted, often a buffered write to a peripheral or a DMA descriptor, and acting on it sends the investigation to the wrong function. The check is cheap: read CFSR first, branch on precise versus imprecise, and only then disassemble at the stacked PC.

Two failure modes bite in the field. First, if the fault handler runs at a priority that cannot preempt a fault already in progress, or if the fault is a stacking error, the core escalates to HardFault with FORCED clear and the original CFSR may be lost. I log CFSR, HFSR, BFAR, MMFAR, stacked PC/LR/xPSR and the active stack pointer to a no-init section on the first entry only, guarded by a flag, so a second fault inside the handler does not overwrite the evidence. Second, reading BFAR without checking BFARVALID sends people chasing a stale address. On imprecise faults BFARVALID stays clear for a reason: the core did not capture an address, and the real culprit is usually a buffered write to a peripheral or a DMA descriptor, found by bisecting recent stores rather than by the stacked PC.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-28A sensor ISR misses its deadline only when no debugger is attached, and adding a UART print makes it pass: how would you use RAM logging and a GPIO trace to find the cause without changing the timing?

The 90-second answer

Assume a Cortex-M sensor ISR that should run every 1 ms and finish in under 20 microseconds. In the field it occasionally overruns. With a breakpoint set, or with a UART print inside the ISR, it never does. That is the probe effect. A breakpoint halts the core and can clear pending interrupts. A print at 115200 baud for 20 characters takes about 1.7 ms, which stretches the ISR and changes when the next interrupt arrives. The bug depends on the timing you just changed.

I would stop observing live and record evidence in RAM, then read it out later. A GPIO pin toggled on ISR entry and exit gives an independent timing trace on a logic analyzer. The RAM log gives the internal state that the analyzer cannot see, such as which branch ran or what the sensor value was.

C
// Cortex-M, CMSIS. Called at the top of the sensor ISR.
#define LOG_N 256
typedef struct { uint32_t t; uint16_t value; uint16_t flags; } log_t;
static log_t log_buf[LOG_N];
static volatile uint32_t log_head;

static inline void log_sample(uint16_t value, uint16_t flags) {
    uint32_t i = log_head & (LOG_N - 1); // LOG_N must be a power of two
    log_buf[i].t = DWT->CYCCNT; // free running cycle counter
    log_buf[i].value = value;
    log_buf[i].flags = flags;
    log_head = i + 1; // single writer: only this ISR writes log_head
}

The log call takes roughly 15 to 25 cycles. At 168 MHz that is under 0.15 microseconds, compared with 1.7 ms for the print. I log only from this ISR, so there is no race on log_head. If a task also needed to log, I would move logging to one context or mask interrupts around the update.

Comparing the three approaches

MethodCost per eventWhat it showsMain limit
UART print in ISRAbout 1.7 ms for 20 chars at 115200 baudHuman readable textChanges the timing under test, can block on TX FIFO
RAM ring bufferAbout 0.1 microsecondsTimestamp, value, flags for the last 256 eventsNeeds a later dump over SWD, RTT or UART, buffer can wrap
GPIO toggle plus logic analyzer2 instructions, under 0.02 microsecondsISR period, jitter and duration on the wireShows timing only, no internal state

I use the last two together. The analyzer tells me whether the ISR is late, long, or both. The log tells me what the ISR saw when it was late.

A worked trace, with hypothetical figures, shows the pattern I look for:

Analyzer measurementExpectedObservedReading
ISR period1000 microseconds1000 microseconds most cycles, 1180 microseconds once per secondSomething preempts it about once per second
ISR duration, entry to exitUnder 20 microseconds14 microsecondsThe ISR code itself is not the problem
Log entry at the late cycleNormal flagsflags shows DMA busy bit setThe late cycle coincides with a DMA transfer

That points to a specific check. I look at whether the DMA completion interrupt has a higher priority than the sensor ISR, or whether the sensor ISR is delayed while a shared peripheral lock is held. I can confirm it by raising the sensor ISR priority by one level in a test build and watching whether the 1180 microsecond period disappears on the analyzer. If it does, the fix is a priority change, not faster sensor code.

period late duration long Fault only with no debugger attached Toggle GPIO at ISR entry and exit Record period and duration on logic analyzer Log timestamp and flags in RAM ring buffer Period late or duration long? Check preemption by higher priority ISR Check work inside the ISR itself

Failure modes to watch

The ring buffer wraps. At 1 kHz, 256 entries cover 256 ms, so a fault once per second can be overwritten before I dump it. I add a separate counter for total events and for overruns, and I dump the buffer on demand with a button or a UART command rather than waiting for a reset. If the device resets on the fault, startup code that zeroes .bss will erase the log. I place the buffer in a noinit section and check a magic word at startup before clearing it, and I record the reset cause so a watchdog reset is not confused with power on.

The DWT counter also wraps. At 168 MHz a 32 bit counter wraps every 25.5 seconds. I compare deltas between consecutive entries, not absolute values, so a wrap between two samples shows as a large delta that I can spot and ignore.

I leave the log in the build behind a compile time flag. After the fix, the analyzer should show a period within a few microseconds of 1 ms over a long run, and the log should show no DMA busy flag on late cycles. If the late period remains, the trace has ruled out the ISR body and the next step is the priority configuration, which is a smaller change to test than rewriting the driver.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-29Walk me through which C++ features you would allow or ban in bare-metal firmware, and how you would measure their size and latency cost on a Cortex-M4?

I would allow RAII, templates, constexpr and unique_ptr, ban exceptions, RTTI and shared_ptr, and allow virtual functions only outside interrupt handlers. The test is whether a feature adds hidden allocation, hidden tables, or unbounded time. I check that on the target, not by opinion. On a Cortex-M4 at 168 MHz I build with -fno-exceptions -fno-rtti, compare the linker map and arm-none-eabi-size between builds, and time the hot path with DWT_CYCCNT.

Exceptions are a ban. Even if nothing throws, the compiler emits unwind tables and landing pads, and a throw that does happen walks destructors for an unbounded time. RTTI pulls in typeinfo and __cxa helpers for dynamic_cast, which I replace with a log line or an explicit type tag. If a library needs either, it does not go into bare-metal code. Errors return a code or call a fault handler I control.

A virtual call is a load of the vptr plus an indirect branch, and the target cannot be inlined. That is fine for a driver interface called from task context, such as a sensor read() called at 10 Hz. It is a poor fit in a 1 kHz control ISR where I want the compiler to inline and where worst-case timing must be bounded. There I use a template or a function pointer fixed at init. The size cost is concrete. With the Itanium ABI on this target each vtable slot is 4 bytes. Two header slots, offset-to-top and the RTTI pointer, plus two virtual functions makes 4 slots, so 16 bytes per class in flash, plus a 4-byte vptr per object in SRAM. With -fno-rtti the RTTI slot is still present and set to null, so banning RTTI saves the typeinfo objects and helpers, not that slot. Three such classes cost 48 bytes of flash. I accept that for a driver hierarchy and reject it if it spreads to every instance in the sampling path.

RAII is the feature I want most. A guard that disables interrupts in its constructor and restores them in its destructor cannot be skipped by an early return, and destruction is deterministic. When inlined it costs nothing. unique_ptr with a stateless deleter is also zero overhead, one pointer, same as the raw pointer. shared_ptr is different. It needs a control block, an atomic reference count, and usually a heap allocation. That allocation breaks static allocation and an atomic increment in an ISR can contend with a preempting ISR, so I ban it.

C++
// GCC 12.3 arm-none-eabi-g++, -std=c++17 -fno-exceptions -fno-rtti
class CriticalSection {
public:
    CriticalSection() { __disable_irq(); }
    ~CriticalSection() { __enable_irq(); }
    CriticalSection(const CriticalSection&) = delete;
    CriticalSection& operator=(const CriticalSection&) = delete;
};

struct SpiDeleter {
    void operator()(SpiBus* p) const noexcept { /* static lifetime, no delete */ }
};

// Stateless deleter: sizeof(unique_ptr) == sizeof(SpiBus*)
std::unique_ptr<SpiBus, SpiDeleter> bus{&staticBus};
FeatureSize cost on Cortex-M4Latency costVerdict
RAII guard0 bytes when inlinedA few instructionsAllow
unique_ptr, stateless deleter0 bytes vs raw pointer0 cyclesAllow
Virtual call16 bytes per vtable for 2 functions, 4 bytes per objectIndirect branch, no inliningAllow outside ISRs
shared_ptrControl block plus heap allocationAtomic refcount, unbounded allocationBan
ExceptionsUnwind tables and landing pads in flashUnbounded unwind on throwBan
RTTITypeinfo per polymorphic class plus __cxa helpersRuntime cast walkBan

Two failure modes I check in review. A missing virtual destructor on a base class means deleting through the base skips the derived destructor and leaks a DMA buffer. A shared_ptr or a throwing allocation created in an ISR fragments the heap over months of uptime, which shows up in a heap watermark long before it crashes.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-30How do you set, clear, toggle and test a 3-bit field at bits 5 to 7 of a 32-bit control register in C without disturbing the other bits?

The 90-second answer

Build one mask for the field, then use the same mask for every operation. For a field starting at bit s with width w in a uint32_t register:

C
#define FIELD_SHIFT 5
#define FIELD_WIDTH 3
#define FIELD_MASK ((((uint32_t)1 << FIELD_WIDTH) - 1u) << FIELD_SHIFT) /* 0xE0 */

static inline void field_set(volatile uint32_t *reg, uint32_t value)
{
    uint32_t v = (value << FIELD_SHIFT) & FIELD_MASK;
    *reg = (*reg & ~FIELD_MASK) | v;
}

static inline void field_clear(volatile uint32_t *reg)
{
    *reg &= ~FIELD_MASK;
}

static inline void field_toggle(volatile uint32_t *reg)
{
    *reg ^= FIELD_MASK;
}

static inline uint32_t field_get(volatile uint32_t *reg)
{
    return (*reg >> FIELD_SHIFT) & (((uint32_t)1 << FIELD_WIDTH) - 1u);
}

static inline int field_is_set(volatile uint32_t *reg)
{
    return (*reg & FIELD_MASK) == FIELD_MASK;
}

field_set clears the old field first, then ORs in the new value. That order matters. reg |= value alone would leave stale 1 bits set when the new value has zeros where the old value had ones.

Why the mask works

((1u << w) - 1u) gives w low bits set. Shifting left by s moves that run to the field position. For s = 5, w = 3: 0b111 << 5 = 0b11100000 = 0xE0. Every operation is then a single bitwise operator against 0xE0:

OperationCodeEffect on field bits
Set all bitsreg |= FIELD_MASK;Forces field to 0b111
Clear all bitsreg &= ~FIELD_MASK;Forces field to 0b000
Toggle all bitsreg ^= FIELD_MASK;Flips each field bit, leaves others alone
Test any bit(reg & FIELD_MASK) != 0True if at least one field bit is 1
Test all bits(reg & FIELD_MASK) == FIELD_MASKTrue only for 0b111
Write a valuereg = (reg & ~FIELD_MASK) | ((v << s) & FIELD_MASK);Replaces field, masks off excess bits in v

The & FIELD_MASK on the shifted value in field_set is not decoration. Without it, a caller passing v = 0xFF would spill bits into the field above. With it, v is truncated to 3 bits.

Worked trace

Start with reg = 0x0000001F. Bits 0 to 4 are set, the field at bits 5 to 7 is 0b000.

StepOperationreg after
1field_set(&reg, 5) where 5 = 0b1010x000000BF (0x1F | 0xA0)
2field_get(&reg)returns 5
3field_toggle(&reg)0x0000005F (field becomes 0b010)
4field_clear(&reg)0x0000001F
5field_is_set(&reg)returns 0

Bits 0 to 4 never change. That is the check to run in a unit test: seed the register with a known pattern outside the field, run each operation, and assert the outside bits are unchanged.

Failure modes worth naming

Shift width. 1u << 32 is undefined behaviour on a 32-bit type, and 1 << 31 on a signed int is undefined behaviour before the shift even happens. Cast to uint32_t or uint64_t first, and handle a full-width field (w = 32) as a special case with mask 0xFFFFFFFFu instead of computing the shift.

Read-modify-write on hardware. The sequence *reg = (*reg & ~mask) | v reads the register, modifies the copy, and writes it back. If the register contains read-to-clear status bits or bits written by hardware, that write can clear status or overwrite a hardware update that landed between the read and the write. The mask logic is correct for a plain control register. It does not make the access atomic, and it does not make it safe for every register type. Check the reference manual for write-1-to-clear and read-to-clear fields before using this pattern on them.

Volatile access count. Passing volatile uint32_t * and dereferencing it twice in field_set reads the hardware register once in the expression *reg & ~FIELD_MASK. That is the intended single read. Writing the helper as separate read and write statements against a macro that expands *reg twice would read it twice, which can return different values on a live status register. The inline functions above keep one read and one write.

A common interview follow-up is whether ~FIELD_MASK needs a cast. FIELD_MASK is already uint32_t, so ~FIELD_MASK is also uint32_t with the field bits zero and every other bit one. ANDing with it clears exactly the field and preserves the rest, including the top bits of the 32-bit word.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-31Two processors exchange a C struct over UART, one little-endian and one big-endian, and frames parse but values are wrong: how do endianness, packing and alignment cause that, and how would you fix the wire format?

The 90-second answer

Sending a C struct over a wire sends the compiler's memory layout, not a protocol. Endianness decides the byte order of each multi-byte field, and packing and alignment decide where each field starts. Change either processor, compiler, or target architecture and the same source produces different bytes, or the same bytes decode to different values. The fix is to define the wire format byte by byte and serialize and deserialize explicitly, never to cast a struct to a buffer.

Take this frame, sent from a little-endian Cortex-M to a big-endian DSP:

C
struct Frame {
    uint8_t  type;
    uint32_t seq;
    uint16_t len;
    uint8_t  payload[8];
};

On a 32-bit little-endian target with default alignment, sizeof(struct Frame) is 20, not 18. type sits at offset 0, then 3 padding bytes align seq to offset 4, len sits at offset 8, payload sits at offset 10, and 2 tail padding bytes bring the size to a multiple of 4. A 16-bit compiler, a different ABI, or a #pragma pack(1) build gives a different layout again. If the receiver was built with packing enabled, it reads seq from offset 1 and every field after type is shifted.

Endianness breaks it even when the offsets happen to match. For seq = 0x01020304:

FieldLittle-endian bytes on wireBig-endian receiver reads as
seq04 03 02 010x04030201 (67,305,985)
len = 0x020000 020x0002 (2, instead of 512)

The frame still parses. type is a single byte, so it survives. Length and sequence look plausible but are wrong, which is why this fails in the field as corrupt payloads and dropped frames rather than as a clean handshake error.

Why packing is worse than it looks

Padding is not the only variable. int, long, enum, bool, and pointers have implementation-defined sizes, and bit-fields have implementation-defined allocation order. Two compilers can disagree on sizeof for a struct that contains only fixed-width types if their alignment rules differ. Marking a struct __attribute__((packed)) removes padding on GCC and Clang, but it does not fix endianness, it does not make the layout portable to MSVC or IAR, and it can generate unaligned accesses. On a Cortex-M0 or on some DSPs, a packed uint32_t member accessed through the struct raises a HardFault. On a Cortex-M3 or M4 it may work slowly, which hides the bug until the code moves.

The wire format I would ship

Define the format as a byte sequence with a version, then encode integers with explicit shifts. The wire header below is not the in-memory struct. It adds a 2-byte magic and a version byte, and it places fields at fixed offsets with no padding.

C
#define FRAME_HDR_LEN 10  /* magic(2) ver(1) type(1) len(2) seq(4) */

static void put_u16le(uint8_t *p, uint16_t v) { p[0] = v & 0xFF; p[1] = (v >> 8) & 0xFF; }
static void put_u32le(uint8_t *p, uint32_t v) { put_u16le(p, (uint16_t)v); put_u16le(p + 2, (uint16_t)(v >> 16)); }
static uint16_t get_u16le(const uint8_t *p) { return (uint16_t)p[0] | ((uint16_t)p[1] << 8); }
static uint32_t get_u32le(const uint8_t *p) { return (uint32_t)get_u16le(p) | ((uint32_t)get_u16le(p + 2) << 16); }

/* Encode: 10-byte header, then payload, then CRC16 over header and payload.
   Decode mirrors this byte for byte and rejects unknown versions before
   touching the payload. */

The receiver checks magic and version, reads len with get_u16le and seq with get_u32le, confirms the received byte count matches, and only then copies the payload into a local struct that is built field by field. That local struct can use natural alignment, because it never crosses the wire.

Two checks catch regressions in CI. First, static_assert on the encoded header size and on a golden byte vector: encoding seq = 0x01020304 must produce 04 03 02 01 at header offset 6 on every host, including when the test runs on a big-endian machine. Second, a loopback test that feeds the encoder output to the decoder with a byte-swapped variant, which fails loudly if anyone reintroduces a struct cast.

If bandwidth is tight, a packed struct with a compile-time size assertion is acceptable as a stopgap on a single compiler pair. It is not a protocol, and it will break silently the first time either side changes toolchain, optimization level, or processor. Explicit serialization costs a few shifts per field and removes that entire class of failure.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-32Walk me through implementing fixed-point scaling for a 12-bit ADC sensor in C, choosing Q format and handling overflow and saturation without floating point?

The 90-second answer

Pick Q format from range first, resolution second, then do every multiply in a wider type and saturate before you narrow. For a 12-bit ADC reading 0 to 4095 mapped to 0 to 10.00 bar, I would use signed Q8.8 for the scaled value. Qm.n means m integer bits including the sign for signed types, n fractional bits, step size 2^-n, and range roughly -2^(m-1) to 2^(m-1) minus one step.

Format (signed 16-bit)RangeStepFits 0 to 10 bar?
Q8.8-128 to 127.9960.00390625Yes, fine resolution
Q12.4-2048 to 2047.93750.0625Yes, coarse
Q15.1-16384 to 16383.50.5Yes, too coarse

Q8.8 wins here because 10 bar needs only 4 integer bits, so spending 8 bits on fraction buys resolution for free. If the sensor could spike to 200 bar on a fault, Q8.8 would saturate at 127.996 and hide the magnitude. That is the trade-off to state out loud: headroom versus resolution in a fixed width.

Scaling without overflow

Raw ADC counts are integers, so the clean path is engineering = raw * gain_num / gain_den, with gain expressed as a fixed-point constant. Precompute the constant at build time, keep the multiply in 64-bit or checked 32-bit, add rounding before the shift, then clamp.

C
#include <stdint.h>

/* Q8.8 result, input raw 0..4095, full scale 10.00 bar.
   gain = 10.00 / 4095 = 0.002442 bar/count.
   In Q16.16 that is 0.002442 * 65536 = 160.06, rounded to 160. */
#define GAIN_Q16 160

static int16_t adc_to_bar_q8(uint16_t raw)
{
    int64_t product = (int64_t)raw * GAIN_Q16; /* bar * 65536 */
    int64_t rounded = product + (1 << 7);      /* half an LSB of Q8.8: 128 in product units */
    int64_t q8 = rounded >> 8;                 /* *65536 -> *256 */

    if (q8 > INT16_MAX) return INT16_MAX;      /* saturate, never wrap */
    if (q8 < INT16_MIN) return INT16_MIN;
    return (int16_t)q8;
}

Worked trace. At raw 2048, product is 327680, plus 128 gives 327808, shifted right 8 gives 1280 in Q8.8, which is 1280 / 256 = 5.0 bar. Expected: 2048 * 10 / 4095 = 5.001 bar. The residual error is from rounding the gain to 160: 160 / 65536 = 0.0024414 bar/count against the exact 0.0024420, an error of about 0.02 percent, or 0.001 bar at mid-scale. That is well under one Q8.8 step of 0.0039 bar, so it does not change the output here. If it did, I would use a larger gain constant, Q24.8, or calibrate with two points and store the offset as well.

Saturation versus wraparound

In C, signed overflow is undefined behaviour, and on the wire a wrapped 16-bit value jumps from +32767 to -32768. For a pressure or temperature reading that feeds a control loop, a wrap looks like a sudden full-scale negative spike and can trip a valve or heater. Saturation clamps to the rail, so the loop sees a large but plausible value and a separate over-range flag can be set. I set that flag in the same branch that clamps, because a saturated reading with no flag is indistinguishable from a genuine rail reading.

Three failure modes I check for. First, the intermediate: raw * gain in 16-bit or even 32-bit can overflow before the shift brings it back in range, so the widening cast must happen before the multiply, as above. Second, the left shift: converting a Q8.8 value back to an integer by << 8 in a 16-bit type overflows for any value above 127, so do that shift in 32-bit and clamp on the way down. Third, sign handling: right-shifting a negative signed value is implementation-defined in older C standards, though GCC and Clang define it as arithmetic shift, so I keep the shifted quantity signed and test the negative path with a negative calibration offset in unit tests.

If the sensor is signed to start with, for example a thermocouple at -40 to 125 degrees C, I would offset the ADC counts to a signed range first, use Q8.8 for the result, and add the offset in the wider type before clamping. Rounding for negative numbers needs care: adding half an LSB before an arithmetic shift rounds toward positive infinity, which biases negative readings by up to one step. For a display that bias is invisible. For an integrator it accumulates, so I would either truncate deliberately and document it, or add the rounding term with the sign of the product.

On a Cortex-M4 with a single-cycle multiplier and no FPU, this whole path is a handful of instructions and runs in the ISR budget. On a part with an FPU the question becomes whether the compiler will emit a software float routine anyway, which is slower and larger. Fixed point also keeps the worst-case timing deterministic, which matters when the scaling runs inside a 1 kHz loop with a 20 microsecond budget.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-33Your Cortex-M0 without an FPU runs a 1 kHz loop that needs a sine value each cycle: how would you decide between software floating point and a fixed-point lookup table, and what would you check?

The 90-second answer

On a Cortex-M0 there is no floating point hardware, so the compiler emits software routines for every float operation. Those routines unpack the exponent and mantissa, do integer arithmetic, and repack the result. A single sine call can therefore cost thousands of cycles, while a table lookup costs tens.

I would not choose by preference. I would measure the float version on the actual chip, compare it with the 1 kHz budget, and only replace it if it does not fit with margin. If it does not fit, a fixed point lookup table is usually the right replacement for sine because the input is a phase that wraps from 0 to 2 pi, the output range is known, and the function is smooth.

Measure the float cost first

Assume a 48 MHz Cortex-M0. At 1 kHz the loop has 48,000 cycles per period. A typical software sinf on this class of core takes roughly 1,000 to 2,500 cycles, depending on the library and the input. That is 2 to 5 percent of the period for one call. If the loop computes one sine and a few multiplies, float may pass. If it computes sines for three phases, or adds a division, the cost climbs quickly and leaves little room for interrupts.

I measure worst case, not average. I set a GPIO at the start and end of the calculation and check the pulse width on a scope while the rest of the system is running, or I read the DWT cycle counter around the call. Average timing hides the input that triggers the slowest path in the library.

ApproachApprox. cycles per sineFlash costError
Software sinf1,000 to 2,500Library code, often 1 to 2 KBNear exact for float
256 entry Q15 table, no interpolation10 to 20512 bytesAbout 0.0002 peak
256 entry Q15 table, linear interpolation20 to 40512 bytesAbout 0.00002 peak

The table wins on cycles by a factor of 50 or more. The question is whether its error is acceptable for the application.

Build the table version

Q15 stores a value in the range -1.0 to just under 1.0 as a signed 16-bit integer, where 32767 represents just under 1.0. That fits sine exactly, since sine never exceeds 1.0 in magnitude. I generate the table offline with a script, store it in flash, and index it with the phase.

C
/* Generated offline: sin_q15[i] = round(sin(2*pi*i/256) * 32767) */
static const int16_t sin_q15[256] = { /* 256 entries */ };

static inline int16_t sin_lookup(uint16_t phase) /* 0 to 65535 maps to 0 to 2*pi */
{
    uint8_t idx = (uint8_t)(phase >> 8);
    uint8_t frac = (uint8_t)(phase & 0xFF);
    int32_t a = sin_q15[idx];
    int32_t b = sin_q15[(uint8_t)(idx + 1)];
    return (int16_t)(a + ((b - a) * frac >> 8));
}

The top 8 bits of phase select the entry, the low 8 bits interpolate between entries. Without interpolation the error is already small enough for many uses, such as generating a PWM waveform or a test tone. With interpolation the error drops by roughly a factor of ten for a few extra instructions.

Check the error before committing

I compare the table output against sinf on a host over all 65,536 phase values and record the peak error. For a 12-bit DAC or ADC system, an error of 0.0002 is below 1 LSB, so it is invisible. If the application needs more accuracy, I increase the table to 1,024 entries, which costs 2 KB of flash and reduces the error further, or I keep float if the timing allows it.

The main trade-off is accuracy and range against speed. Float handles any input range and needs no error analysis, but it is slow and its cost is hard to predict. Fixed point is fast and deterministic, but only works when the range is known in advance, as it is for sine. For a bounded, smooth function like this, the table is the better engineering choice once measurement shows float is too expensive. If measurement shows float fits comfortably, keeping float is the better choice, because it removes the table, the scaling, and the error check entirely.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-34What does the C standard say happens on signed integer overflow, and why can that break a timeout check at -O2?

The 90-second answer

Signed integer overflow is undefined behavior in C. The compiler is allowed to assume it never happens. At -O2 it uses that assumption to fold arithmetic and delete branches. A timeout check written with signed int can therefore disappear in the release build even though it worked at -O0.

Unsigned overflow is different. It is defined to wrap modulo 2^32 for uint32_t. That is why tick and deadline code in firmware should use unsigned types and subtraction, not signed addition.

Example: a timeout that vanishes

C
/* GCC 13, Cortex-M4, checked at -O0 and -O2 */
#include <stdint.h>

int32_t now_ms = 2147483600;   /* close to INT32_MAX */
int32_t timeout_ms = 1000;
int32_t deadline = now_ms + timeout_ms;  /* signed overflow: UB */

if (now_ms > deadline) {
    handle_timeout();
}

At -O0, GCC usually emits an add and a compare. The add wraps to a negative value, the compare is true, and handle_timeout() runs. The code appears to work.

At -O2, GCC reasons from the standard. If now_ms + timeout_ms overflowed, the program would have undefined behavior, so on every defined execution the result must be greater than now_ms. It folds now_ms > deadline to false and removes the call. The sensor then never times out in the shipped build.

BuildWhat the compiler assumesResult for the check above
-O0Little optimization, emits the add as writtenWraps, branch taken, timeout fires
-O2Signed overflow never occursBranch folded to false, timeout never fires

The defined form

C
uint32_t start = HAL_GetTick();
uint32_t timeout = 1000;

if ((uint32_t)(HAL_GetTick() - start) >= timeout) {
    handle_timeout();
}

Unsigned subtraction wraps in a defined way, so the difference stays correct even when the 1 kHz millisecond counter wraps after about 49.7 days. No assumption about overflow is needed, and the optimizer has nothing to fold away.

The practical rule I apply: any arithmetic on tick counts, deadlines, or timer compares uses uint32_t. I also build the release flags in CI with -Wall -Wextra and compare behavior between -O0 and the shipped -O2 or -Os build. If a check only works at -O0, I treat the source as buggy rather than shipping the debug optimization level.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-35Your SPI DMA driver works at -O0 but corrupts frames at -O2, shares a status struct with an ISR, packs bytes through a union, and builds a DMA descriptor on the stack: how do you use MISRA rules and static analysis to separate the volatile, aliasing and uninitialized defects and fix them without breaking ISR timing?

The 90-second answer

I would assume Cortex-M4, C11, GCC or Clang at -O2, a DMA descriptor built on the stack, a status struct shared with an ISR, and byte packing through a union. Three separate defects can produce the same symptom, a corrupted SPI frame, so I would not fix them by inspection alone. I would run the analyser on the release flags, reproduce each defect with a targeted test, and only then rewrite the code. A fix that adds a lock or a second register read to silence the analyser can break the 1 ms ISR budget, so timing has to be checked after the rewrite.

The volatile defect is usually a cast or a copy that drops qualification. The aliasing defect is usually a pointer cast from uint8_t * to uint32_t *, which breaks alignment and effective type rules even when the address happens to work on a Cortex-M4. The uninitialized defect is usually a descriptor field or padding byte that DMA, a checksum, or a wire format then reads. MISRA C:2012 Rule 9.1 covers the last one directly. Rules on essential type, pointer arithmetic and volatile access cover the first two, and the analyser checks them across headers where macros hide the cast.

C
/* Buggy driver fragment, checked with GCC 13 -O2 -Wall -Wextra -fanalyzer */
struct status { volatile uint32_t flags; uint32_t count; };
struct dma_desc { uint32_t src, dst, len, ctrl; };

void spi_kick(struct status *s, uint8_t *buf) {
    uint32_t *p = (uint32_t *)buf;          /* aliasing and alignment risk */
    struct dma_desc d;                      /* ctrl and padding uninitialized */
    d.src = (uint32_t)buf; d.dst = (uint32_t)TXDR; d.len = 64;
    if (s->flags & 1u) { }                  /* volatile read, but see below */
    *p = 0xA5A5A5A5u;
    start_dma(&d);
}

/* Fixed fragment */
void spi_kick(struct status *s, const uint8_t *buf) {
    uint32_t flags = s->flags;              /* one volatile read into a local */
    struct dma_desc d = { .src = (uint32_t)buf, .dst = (uint32_t)TXDR,
                          .len = 64, .ctrl = 0 };
    uint32_t word = 0xA5A5A5A5u;
    uint8_t packed[4];
    memcpy(packed, &word, sizeof(word));    /* no pointer cast, no aliasing question */
    if (flags & 1u) { start_dma(&d); }
}

The union case needs care. In C, reading a different union member than the one last written is permitted by GCC and is common for byte packing, but a MISRA profile may still flag it, and the same code in C++ has stricter rules. memcpy removes the argument, compiles to a single STR on Cortex-M4 for a 4-byte copy, and gives the analyser a clean effective type. I would keep a union only where a deviation is recorded and the compiler documents the behaviour.

Symptom at -O2Likely defectTest that separates itFix that preserves ISR timing
Frame correct at -O0, wrong word at -O2Pointer cast reordered or merged by strict aliasing analysisHost build with -fsanitize=alignment,undefined, plus a simulated register file where the buffer address is deliberately offset by 1memcpy through a local uint32_t, one store, no extra instruction in the ISR path
Status bit missed only when the ISR fires during the checkVolatile cast away, or two reads of flags in one expressionTest double that changes flags on every read and counts readsRead once into a local, test the local, keep the read outside any critical section
DMA channel or direction random between buildsUninitialized ctrl, or padding included in a checksum over the descriptorFill the stack with 0xA5 before the call, checksum the descriptor bytes, compare with the expected imageDesignated initializer zeroes the rest, checksum covers named fields only
Works on the bench board, HardFaults on the Cortex-M0 variantUnaligned uint32_t * castCompile the same driver for the M0 target and run the offset-buffer testSame memcpy fix, plus an alignment assertion on any buffer that DMA requires to be aligned

How I run the analysis

Compiler warnings come first, with -Wall -Wextra -Wconversion -Wshadow treated as errors for driver files. That catches truncations and some uninitialized reads, but it does not follow a cast through a shared header. I then run a MISRA-aware analyser, PC-lint Plus, Coverity or IAR C-STAT, on the exact release configuration, including the headers that define the register map. Findings go into a baseline. A suppression needs a comment naming the hardware fact that makes it safe, such as a register block aligned to 4 bytes by the memory map, and a new suppression appears in review. I do not suppress a dropped volatile qualifier or a partially initialized descriptor, because neither has a hardware justification.

For verification I use three small harnesses rather than a general claim that the code is clean. A volatile test double counts reads. A stack pattern fill exposes uninitialized fields, since Valgrind is not available on bare metal. A host build with sanitizers exposes alignment faults that a Cortex-M4 tolerates silently. After the rewrite I remeasure the ISR with a GPIO toggle and a scope or logic analyser, because the memcpy version should be identical in cost to the cast version on this target, and if it is not, that difference is worth knowing before the change ships.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-36Walk me through how you would structure a UART driver with a register layer and a portable API, and what you would keep out of HAL and in application code?

The 90-second answer

I split a UART driver into three layers. The register layer knows the datasheet for one part: base address, offsets, bit fields, volatile access. The portable API, the HAL, knows the peripheral as a device: clocks, pins, interrupts, DMA, bounded waits, error codes. Application code knows the product: framing, checksums, retries, and what a timeout means.

That split lets the same protocol code move from polling to DMA, or from one STM32 family to another, without touching the application. If application code writes a register bit directly, or HAL code decides to retry a packet, the layers have leaked.

Register layer, STM32F407 USART1

USART1 sits at 0x40011000 on the STM32F407. Its register order in RM0368, section 19.5, is SR at 0x00, DR at 0x04, BRR at 0x08, CR1 at 0x0C, CR2 at 0x10, CR3 at 0x14. One struct per instance, fields volatile, no logic beyond typed accessors.

C
/* STM32F407 USART, checked against RM0368 */
typedef struct {
    volatile uint32_t SR;   /* 0x00 status */
    volatile uint32_t DR;   /* 0x04 data */
    volatile uint32_t BRR;  /* 0x08 baud rate */
    volatile uint32_t CR1;  /* 0x0C control 1 */
    volatile uint32_t CR2;  /* 0x10 control 2 */
    volatile uint32_t CR3;  /* 0x14 control 3 */
} usart_regs_t;

#define USART1_BASE 0x40011000u
static usart_regs_t *const usart1 = (usart_regs_t *)USART1_BASE;

#define USART_CR1_UE   (1u << 13)
#define USART_CR1_TE   (1u << 3)
#define USART_CR1_RE   (1u << 2)
#define USART_SR_TXE   (1u << 7)
#define USART_SR_RXNE  (1u << 5)

The register layer never computes baud from a clock frequency. That needs the clock tree, which belongs one layer up.

Portable API (HAL)

The HAL takes a plain config struct, owns clock enable, GPIO alternate function setup, interrupt and DMA setup, and returns an error enum. Every wait is bounded.

C
typedef enum { HAL_OK = 0, HAL_BUSY, HAL_TIMEOUT, HAL_PARAM } hal_status_t;

typedef struct {
    uint32_t baud;      /* e.g. 115200 */
    uint8_t  data_bits; /* 8 or 9 */
    uint8_t  parity;    /* 0 none, 1 even, 2 odd */
    uint8_t  stop_bits; /* 1 or 2 */
} hal_uart_config_t;

hal_status_t hal_uart_init(uint8_t instance, const hal_uart_config_t *cfg);
hal_status_t hal_uart_write(uint8_t instance, const uint8_t *buf, size_t len, uint32_t timeout_ms);
hal_status_t hal_uart_read(uint8_t instance, uint8_t *buf, size_t len, uint32_t timeout_ms);

Two rules keep it portable. No register names or bit positions appear in any header the application includes. And no HAL function spins forever on a status bit. A wiring fault then returns HAL_TIMEOUT instead of hanging the device.

Interrupts and DMA also live here. The ISR moves bytes into a 256-byte ring buffer owned by the HAL and sets a flag. At 115200 baud 8N1 the line carries 11520 bytes per second, so 256 bytes cover about 22 ms of receive data while a task is delayed. The HAL does not parse frames. To wake a task it calls a callback the application registered at init, rather than calling RTOS primitives directly, so the same HAL works bare metal and under FreeRTOS.

Baud calculation, worked example

On the F407, USART1 hangs off PCLK2. With the common 84 MHz PCLK2, RM0368 gives BRR = PCLK2 / baud for oversampling by 16.

Target baudBRR (decimal, hex)Actual baudError
96008750, 0x222E96000.00%
115200729, 0x02D9115226+0.02%
230400365, 0x016D230137-0.11%

The HAL computes BRR from the actual PCLK2 it reads from the clock driver, checks the error against a 2% budget, and returns HAL_PARAM if the requested baud cannot be met. The register layer only stores the resulting value in BRR.

Application code

Application code owns packet format, sequence numbers, retry count, backoff, and recovery after repeated timeouts. It calls hal_uart_write with a complete frame and treats HAL_TIMEOUT as a line fault or a peer that stopped responding.

LayerOwnsMust not own
RegisterBase address, offsets, masks, volatile accessBaud calculation, timeouts, retries
HALClock and pin setup, IRQ, DMA, bounded waits, error codesFraming, checksums, retry policy
ApplicationProtocol, retry policy, logging, recoveryRegister bits, clock registers, ISR entry

Where the split breaks

The common failure is a HAL that returns raw SR values, so application code branches on status bits and the driver cannot be ported. The fix is to map every hardware condition to the error enum at the HAL boundary.

The opposite failure is application code polling TXE in a loop because the HAL only offers a blocking write. At 115200 baud one byte takes about 87 microseconds on the wire, and a polling loop burns that CPU time per byte. The fix is an interrupt or DMA path with a completion callback, not a poll spread through the application.

A third failure is a blocking HAL call from inside an ISR, for example waiting for TXE while the UART interrupt is masked. The ISR never exits and lower priority work starves. The rule that prevents it: from interrupt context the HAL transmit and receive calls are non-blocking and return HAL_BUSY if the ring buffer is full.

Application: protocol, retries Portable API: hal_uart_* Register layer: struct, masks Clock, pins, IRQ, DMA USART hardware

To test the split, I compile the application against a mock HAL on the host and run protocol tests with no hardware attached. If that fails, the application knows too much about the peripheral. I also compile the HAL against a second register header with different offsets. If only that header changes, the layers are doing their job.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-37How would you configure GPIO mode, pull, drive strength and slew rate for I2C lines, an SPI bus and a status LED, and why does each differ?

The 90-second answer

I2C gets open-drain with pull-ups. SPI gets push-pull with no pull. An LED gets push-pull if the GPIO sources current, or open-drain if it sinks current to ground. The mode decides who can pull the line low, the pull decides the idle level when nobody drives, and drive strength plus slew rate decide how fast the edge moves into the load.

Open-drain can only pull low. The transistor turns on to pull down, and turns off to let the pull-up resistor pull high. That is what I2C needs. Multiple devices share SCL and SDA, any of them can pull low to send ACK, NACK or clock stretching, and none of them ever actively drives high. If you configure I2C as push-pull, a master driving high while a slave pulls low is a direct contention between two output stages. The bus can stick, corrupt ACK, and stress the pins.

SPI is different. The controller drives SCK and MOSI, the peripheral drives MISO, and only one side drives each line at a time. Push-pull drives both high and low actively, so edges are fast and symmetric and the line does not depend on a resistor to rise. A pull on SPI only matters before the pin is configured, to stop a floating chip select from asserting during reset.

SignalModePullWhy
I2C SCL, SDAOpen-drain, alternate functionExternal pull-up, internal pull-up off if external fittedAny device can pull low, nobody drives high, idle is high
SPI SCK, MOSI, CSPush-pull, alternate functionNoneActive drive both ways, fast edges into trace and input capacitance
SPI MISOPush-pull or input, alternate functionNone, or pull-up if peripheral may be absentPeripheral drives when selected, pull only holds idle level
LED, sourcing from GPIOPush-pull outputNoneGPIO drives high, resistor sets current
LED, sinking to groundOpen-drain outputNoneGPIO pulls low to light, releasing the pin turns it off
Unused inputInputPull-down or pull-up, whichever matches the circuitFloating CMOS input draws leakage and picks up noise

Pull-up sizing for I2C. The internal pull-up on many Cortex-M parts is in the tens of kilohms, commonly specified around 30 kΩ to 50 kΩ depending on the part and voltage. That is fine for a slow GPIO input and too weak for a 400 kHz bus. Rise time is set by the resistor charging the bus capacitance: t_r is about 0.85 x R_p x C_b. With 150 pF of bus and trace capacitance and a 4.7 kΩ external pull-up, t_r is about 0.85 x 4700 x 150 pF = 600 ns, which fits the 1000 ns maximum rise time for 400 kHz fast mode. With a 40 kΩ internal pull-up the same calculation gives 0.85 x 40000 x 150 pF = 5.1 µs, so the bus never reaches a valid high before the next bit. I use 2.2 kΩ to 4.7 kΩ external, then check the low side against the actual datasheet for the devices fitted: the pull-up current at 3.3 V is V/R, so 3.3 V / 2.2 kΩ = 1.5 mA, and that current plus any other load must stay inside the IOL and VOL limits in those datasheets. I also check total capacitance against the 400 pF I2C limit.

Drive strength and slew rate. Drive strength is the current the output stage can source or sink, often selected as low, medium or high, or as a GPIO speed setting on STM32. Slew rate is how fast the output voltage moves between rails. A stronger, faster driver charges a capacitive load quickly, which SPI needs at 10 MHz or above into a flash chip with tens of picofarads of input capacitance. The cost is ringing and EMI. A fast edge on a long trace reflects, overshoots past the rails, and radiates. Slowing the slew rate, or adding a small series resistor of 22 Ω to 47 Ω near the driver, damps that ringing and cuts emissions, at the cost of a slower edge that can eat into setup and hold time at the receiver. I start SPI at medium drive, measure with a scope at the peripheral pin, and only raise drive or speed if the edge is too slow or the eye is closed. For an LED, drive strength rarely matters. Current is set by the resistor, not the pin: (3.3 V - 2.0 V) / 330 Ω is about 3.9 mA for a red LED with a 2.0 V forward drop. Pick the resistor for the current you want, then confirm the pin source or sink rating in the datasheet covers it.

C
/* STM32F4-style register setup, 3.3 V board */
/* I2C1 on PB6/PB7: open-drain, alternate function, external pull-ups fitted */
GPIOB->MODER   = (GPIOB->MODER & ~GPIO_MODER_MASK(6,7)) | GPIO_MODER_AF(6,7);
GPIOB->OTYPER  = (GPIOB->OTYPER & ~GPIO_OTYPER_MASK(6,7)) | GPIO_OTYPER_OD(6,7);
GPIOB->PUPDR   = (GPIOB->PUPDR & ~GPIO_PUPDR_MASK(6,7)) | GPIO_PUPDR_NONE(6,7);
GPIOB->OSPEEDR = (GPIOB->OSPEEDR & ~GPIO_OSPEEDR_MASK(6,7)) | GPIO_OSPEEDR_HIGH(6,7);
GPIOB->AFRL    = (GPIOB->AFRL & ~GPIO_AFRL_MASK(6,7)) | GPIO_AF4(6,7);

/* SPI1 on PA5/PA6/PA7: push-pull, no pull */
GPIOA->MODER   = (GPIOA->MODER & ~GPIO_MODER_MASK(5,6,7)) | GPIO_MODER_AF(5,6,7);
GPIOA->OTYPER  = (GPIOA->OTYPER & ~GPIO_OTYPER_MASK(5,6,7)) | GPIO_OTYPER_PP(5,6,7);
GPIOA->PUPDR   = (GPIOA->PUPDR & ~GPIO_PUPDR_MASK(5,6,7)) | GPIO_PUPDR_NONE(5,6,7);
GPIOA->OSPEEDR = (GPIOA->OSPEEDR & ~GPIO_OSPEEDR_MASK(5,6,7)) | GPIO_OSPEEDR_MED(5,6,7);
GPIOA->AFRL    = (GPIOA->AFRL & ~GPIO_AFRL_MASK(5,6,7)) | GPIO_AF5(5,6,7);

/* Status LED on PA8, sourcing current through 330 ohm to ground */
GPIOA->MODER   = (GPIOA->MODER & ~GPIO_MODER_MASK(8)) | GPIO_MODER_OUT(8);
GPIOA->OTYPER  = (GPIOA->OTYPER & ~GPIO_OTYPER_MASK(8)) | GPIO_OTYPER_PP(8);
GPIOA->PUPDR   = (GPIOA->PUPDR & ~GPIO_PUPDR_MASK(8)) | GPIO_PUPDR_NONE(8);
GPIOA->OSPEEDR = (GPIOA->OSPEEDR & ~GPIO_OSPEEDR_MASK(8)) | GPIO_OSPEEDR_LOW(8);

Failure modes I check. Push-pull on a shared I2C line shows up as a bus that works at 100 kHz on the bench and fails when a second device is fitted, because contention corrupts ACK and can stick SDA low. A missing pull-up shows up as a rise time that fails the scope check above. An SPI pull-up enabled with no peripheral fitted can hold MISO high and mask a dead device. For the LED, I match wiring to mode and check both states: a sourcing LED (GPIO, resistor, LED, ground) is on when the push-pull pin is high and off when it is low; a sinking LED (3.3 V, resistor, LED, GPIO) is on when the open-drain pin pulls low and off when the pin is released, because there is then no path to ground. Finally, maximum drive on a long SPI trace gives ringing that a logic analyzer will not show, so I look at the waveform at the receiver before I call the configuration done.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-38What is the Nyquist rule for choosing an ADC sampling rate, and what happens if you sample slower than it?

The 90-second answer

Sample at more than twice the highest frequency present at the ADC pin. That is the Nyquist rule: fs > 2 x fmax. If you sample slower, a high frequency signal folds back and appears as a lower frequency that is not really there. That folded signal is aliasing, and no amount of digital filtering after the ADC can remove it because the samples themselves are wrong.

Why it happens

An ADC only sees the signal at the instant of each sample. Between samples it sees nothing. A 6 kHz sine sampled at 10 kS/s can look identical to a 4 kHz sine sampled at the same rate, because the phase advances by the same amount at each sample point. The converter is working correctly. The information needed to tell 6 kHz from 4 kHz was never captured.

The strict inequality matters. At exactly fs = 2 x fmax, a sine sampled at its zero crossings produces all zeros. In practice, use a margin. Five to ten times fmax gives you samples per cycle you can actually plot, filter and measure peaks from.

Worked check

Suppose the signal at the pin is 5 kHz and you want a clean waveform.

Sample rateSamples per cycleResult
10 kS/s2Theoretical limit, fragile
25 kS/s5Usable
50 kS/s10Comfortable
8 kS/s1.6Aliased, appears as 3 kHz

The last row is the one to remember in an interview. The ADC will happily report a steady 3 kHz sine. Nothing in the digital data flags it as wrong.

A quick calculation in code

C
/* Signal at pin: 5 kHz. Choose 10 samples per cycle. */
#define F_SIGNAL_HZ 5000u
#define SAMPLES_PER_CYCLE 10u
#define FS_HZ (F_SIGNAL_HZ * SAMPLES_PER_CYCLE)  /* 50000 Hz */

/* Timer period for a 84 MHz timer clock, prescaler 0: */
#define TIMER_CLK_HZ 84000000u
#define ARR ((TIMER_CLK_HZ / FS_HZ) - 1u)  /* 1679 */

Set the timer to trigger the ADC every ARR + 1 timer clocks, and check that the ADC conversion time fits inside that period. For a 12-bit ADC with a 14 MHz ADC clock and 40 cycles per conversion, conversion takes about 2.86 us, well inside the 20 us period at 50 kS/s.

The practical consequence

fmax means the highest frequency at the pin, not the frequency you care about. A 5 kHz sensor signal on a board with 600 kHz regulator ripple needs either a filter before the pin that removes the ripple, or a sample rate above 1.2 MS/s. Most designs do the first: a simple RC low-pass at the input, then sample at a rate set by the filtered signal. If a reading shows a slow wander that does not match the sensor, aliasing from an unfiltered high frequency source is the first thing to check.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-39Your 84 MHz timer must give inaudible 20 kHz PWM with 12-bit duty resolution and usable 1% pulses through a gate driver with 200 ns dead time, updated every cycle without glitches: how do you pick PSC, ARR and CCR, and what do you change when those constraints conflict?

The 90-second answer

Start from the timer clock, not the core clock, and check whether the three requirements can coexist before writing any register. At 84 MHz, 20 kHz leaves 4,200 counts per period, which just clears 12-bit resolution (4,096 steps). A 1% pulse is then 500 ns, and after 200 ns of dead time plus gate driver delay the FET barely enhances. That conflict, not the arithmetic, is the design problem. I would use preload so duty updates never glitch, verify the real period on a scope, and handle the low-duty end with pulse skipping or a lower frequency at light load rather than pretending 1% works cleanly.

The calculation, with real numbers

Assume an STM32F4 at 168 MHz. TIM2 is on APB1, and because the APB1 prescaler is not 1, its timer clock doubles to 84 MHz. That doubling is the first trap: using 42 MHz or 168 MHz in the formula gives a frequency wrong by a factor of two or four.

f_pwm = f_tim / ((PSC + 1) * (ARR + 1))
duty  = CCR / (ARR + 1)
resolution_bits = log2(ARR + 1)

For 20 kHz with PSC = 0: ARR + 1 = 84,000,000 / 20,000 = 4,200, so ARR = 4199. That is 4,200 steps, about 12.0 bits. CCR = 2100 gives 50.0%, CCR = 42 gives 1.0%, and CCR = 4199 gives 99.98%. True 100% needs CCR = ARR + 1, which many timers clamp, so I would force a constant level for genuine 0% or 100%.

C
/* STM32F4, TIM2_CH1 on PA0, timer clock 84 MHz, 20 kHz PWM */
#include "stm32f4xx.h"

void pwm_init(void)
{
    RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;

    GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER0) | (2u << 0); /* AF */
    GPIOA->AFRL  = (GPIOA->AFRL & ~GPIO_AFRL_AFSEL0)  | (1u << 0);  /* AF1 */

    TIM2->PSC   = 0;          /* no prescale */
    TIM2->ARR   = 4199;       /* 84 MHz / 4200 = 20 kHz */
    TIM2->CCR1  = 2100;       /* 50% duty */
    TIM2->CCMR1 = TIM_CCMR1_OC1PE;                 /* preload compare */
    TIM2->CCER  = TIM_CCER_CC1E;                   /* enable output */
    TIM2->CR1   = TIM_CR1_ARPE | TIM_CR1_CEN;      /* preload ARR, start */
}

void pwm_set_duty(uint16_t permille) /* 0..1000, called from control loop */
{
    uint32_t ccr = ((uint32_t)permille * 4200u) / 1000u;
    if (ccr > 4199u) ccr = 4199u;
    TIM2->CCR1 = ccr; /* latches at next update event, no runt pulse */
}

Preload is not optional when the loop updates every cycle. Without OC1PE and ARPE, a write landing mid-period can produce one cycle mixing the old compare with the new period, or a runt pulse. With preload, both registers latch on the update event, so the waveform stays periodic.

Target frequencyCounts at 84 MHzResolutionConsequence
1 kHz84,00016.4 bitsFine dimming, audible whine, large ripple
20 kHz4,20012.0 bitsInaudible to most, meets 12-bit target barely
100 kHz8409.7 bitsFails 12-bit target, higher switching loss
500 kHz1687.4 bitsToo coarse for smooth control

Where the constraints collide

At 20 kHz the period is 50 us. One count is 11.9 ns, so 12-bit resolution is real. But 1% duty is a 500 ns pulse. Subtract 200 ns dead time and, say, 80 ns of driver propagation delay, and the FET sees under 250 ns of gate drive. It may never fully enhance, so measured duty at the low end compresses and the converter drops out of regulation at light load. Raising frequency makes this worse: at 100 kHz, 1% is 100 ns, shorter than the dead time itself.

Audible noise pushes frequency up, efficiency pushes it down. Switching loss rises roughly with frequency because each cycle charges the gate and output capacitance, and dead time costs a fixed fraction that grows with frequency: 200 ns is 0.4% of a 20 kHz period but 2% of a 100 kHz period, distorting low duty most. Ripple pushes frequency up. For a buck inductor, peak-to-peak ripple is about V * D * (1 - D) / (L * f_pwm). At 12 V, D = 0.5, L = 10 uH, that is 150 mA at 20 kHz and 3 A at 1 kHz, which is extra RMS heating and torque ripple. So 20 kHz is a compromise, not a default: quiet enough, ripple manageable with a 10 uH inductor, switching loss still modest. I would confirm it by measuring input power against load at 20 kHz and 40 kHz rather than trusting a datasheet curve.

What I change when it does not fit

If 12-bit resolution and 20 kHz cannot both hold on a slower timer clock, the honest options are a higher timer clock, a different timer on a faster bus, or duty dithering across cycles to average finer steps. Dithering adds ripple at the dither rate, so it suits LED dimming better than a current loop.

For the 1% pulse problem, I would not chase it with a faster timer. I would set a minimum duty of about 2 to 3% in continuous mode and use pulse skipping below that: emit full 20 kHz pulses at the minimum width on some cycles and skip others, so average output falls without ever issuing a sub-dead-time pulse. That trades a little more output ripple at light load for clean switching. The alternative, lowering frequency at light load, reintroduces audible noise and larger ripple, so I would only do it if the load is a motor that tolerates it.

Finally, I verify with a scope on the gate and the output, not the register values. I check the period against the calculation, look for a glitch when the loop writes CCR1 at full rate, and measure the actual pulse width at 1% and 2% duty. If the FET gate never reaches its plateau at 1%, the design has told me the answer, and pulse skipping is the fix.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-40How would you use timer input capture and encoder mode to measure a 1 kHz to 50 kHz signal and a quadrature encoder's position, handling counter overflow and capture latency?

The 90-second answer

Use the timer hardware to timestamp edges, not the ISR to poll them. In input capture mode the counter keeps running and the capture register latches CNT on the selected edge. In encoder mode (TI1/TI2) the same counter counts quadrature pulses and sets direction from the phase order. The ISR then only reads latched values and extends them to 32 bits. That separation keeps measurement error at one timer tick instead of one ISR latency.

Assume a 16-bit timer clocked at 72 MHz with prescaler 0, so one tick is 13.9 ns and the counter wraps every 65536 ticks, or 0.91 ms. A 1 kHz signal has a period of 72000 ticks, so it wraps just over once per period. A 50 kHz signal has a period of 1440 ticks and fits comfortably. Overflow is therefore part of the timestamp, not an error case.

C
// STM32-style TIM, 16-bit CNT, 72 MHz, capture on TI1FP1 rising edge
volatile uint32_t g_overflow = 0;
volatile uint32_t g_last_capture = 0;
volatile uint32_t g_period_ticks = 0;
volatile uint32_t g_overcapture_count = 0;

void TIMx_IRQHandler(void) {
    if (TIMx->SR & TIM_SR_UIF) {          // update: CNT wrapped
        TIMx->SR &= ~TIM_SR_UIF;
        g_overflow++;
    }
    if (TIMx->SR & TIM_SR_CC1IF) {
        uint32_t ovf = g_overflow;
        uint32_t cap = TIMx->CCR1;        // latched at the edge
        TIMx->SR &= ~TIM_SR_CC1IF;
        if (TIMx->SR & TIM_SR_CC1OF) {    // overcapture: a newer edge overwrote CCR1
            TIMx->SR &= ~TIM_SR_CC1OF;
            g_overcapture_count++;
            g_last_capture = 0;           // lost edge cannot be reconstructed; resync
            return;
        }
        uint32_t stamp = (ovf << 16) | cap;
        if (g_last_capture) g_period_ticks = stamp - g_last_capture;
        g_last_capture = stamp;
    }
}

Overcapture needs care. It means the previous captured value in CCR1 was overwritten before the ISR read it, so that edge's timestamp is gone. Incrementing the overflow count would not recover it, because the overflow count tracks CNT wraps, not missed captures. The correct action is to discard the period that spans the lost edge, count the event for diagnostics, and resync on the next clean capture. If overcapture fires repeatedly, the ISR is too slow or the signal is too fast for the chosen prescaler, and no period is trustworthy until that is fixed.

Worked trace for a 10 kHz signal, nominal period 7200 ticks, with the counter wrapping mid-period:

EdgeCNT latchedOverflow countExtended stampDelta
1600002191072-
2166031982687196
3886432054727204
41606432126727200

The deltas average to 7200 ticks, which is 7200 / 72e6 = 100 µs, or 10 kHz. Individual deltas vary by a few ticks from input filter delay and signal jitter, not from ISR timing, because CCR1 was latched in hardware. Frequency is timer_clock / period_ticks. For a gate measurement over N periods, use (stamp_N - stamp_0) / N to average out jitter.

Encoder mode is the same counter with a different clock source. With TI12 mode, both TI1 and TI2 clock the counter, direction follows the phase sequence, and ARR sets the wrap point. Set ARR to counts_per_rev - 1 for a clean modulo position, or to 65535 and extend in software for an unbounded position. A 2048 CPR encoder in x4 mode gives 8192 counts per revolution. At 3000 rpm that is 409600 counts per second, so a 16-bit counter wraps about 6.25 times per second. The update interrupt extends CNT to a signed 32-bit position, and direction comes from the DIR bit rather than from software decoding.

Signal edge Input filter and prescaler Capture register latches CNT CCxIF interrupt Read CCRx and overflow count Extend to 32-bit stamp Compute period or position Counter wrap UIF interrupt
MethodTimestamp sourceError sourceUse it when
Input captureHardware latch of CNTFilter delay, overcapture if ISR lagsFrequency, period, pulse width
Encoder modeHardware quadrature counterMissed counts above max count ratePosition, velocity, direction
GPIO polling in ISRTime ISR runsFull ISR latency and jitter, often 1 to 20 µsNothing at these rates, debug only

Latency has two parts. Capture latency is fixed: the input filter (set IC1F to reject spikes shorter than a few ticks) plus one tick of synchronisation. ISR latency does not move the timestamp, it only risks overcapture. That is why a 50 kHz signal is fine with a 5 µs ISR, period 20 µs, but a 500 kHz signal on the same setup will overcapture unless the prescaler divides the input or DMA moves CCRx to memory. For encoder velocity, sample the extended position at a fixed 1 kHz control rate and differentiate, rather than timing each pulse, because pulse timing at high count rates wastes ISR bandwidth.

Two checks before trusting the numbers: confirm the timer clock with a scope on a toggle output, since a prescaler or PLL change silently rescales every result, and inject a known 1 kHz square wave and verify the computed frequency within one tick in 72000. If the reading drifts with load, look for overcapture flags and for a shared timer being reconfigured by another driver.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-41Your I2C EEPROM driver writes 64 bytes at address 0x003E and the first bytes corrupt and reads right after a write fail: how do you handle page boundaries, write cycles and ACK polling in code?

The 90-second answer

An I2C EEPROM such as a 24LC256 does not accept a new command while it is copying data from its write latch into the array. That internal cycle takes up to 5 ms on that part, 10 ms max in the datasheet, and the device signals it by NACKing its device address. ACK polling is how you wait for it: after a STOP, repeatedly send START plus the device address with R/W = 0 until you get an ACK, then STOP. A NACK during that poll is expected. A NACK during the data phase of a write is a different fault.

The second trap is the page latch. The 24LC256 has a 64-byte page. If a write starts at offset 60 in a page and you send 8 bytes, bytes 5 to 8 do not go to the next page. They wrap to offset 0 of the same page and overwrite the first 4 bytes you just wrote. The bus transaction completes cleanly and returns ACKs, so the corruption is silent. The fix is to split every write at the page boundary before it reaches the bus, and to ACK poll after every chunk, not just at the end of the buffer.

C
// Checked against Microchip 24LC256 datasheet: 64-byte page, 5 ms typical write cycle.
#define EEPROM_PAGE 64
#define ACK_POLL_TIMEOUT_MS 20

int eeprom_write(uint8_t dev_addr, uint16_t addr, const uint8_t *buf, size_t len)
{
    while (len > 0) {
        size_t chunk = EEPROM_PAGE - (addr % EEPROM_PAGE);
        if (chunk > len) chunk = len;

        if (i2c_write(dev_addr, addr, buf, chunk) != 0) return -1; // data-phase NACK: bus or address fault
        if (ack_poll(dev_addr, ACK_POLL_TIMEOUT_MS) != 0) return -1; // still NACKing after 20 ms: device absent or stuck

        addr += chunk;
        buf  += chunk;
        len  -= chunk;
    }
    return 0;
}

ack_poll sends only START, address, R/W = 0, and STOP on ACK. It must not send a memory address or data, because some parts treat a full write frame during the cycle as a new write attempt. Poll every 1 ms, which bounds the added latency to about one poll interval after the 5 ms cycle instead of a fixed 10 ms sleep per chunk.

Worked trace: 8 bytes at 0x003E, page size 16 for readability

StepBus actionResult if done naivelyResult with chunking
1Write 8 bytes starting at 0x003EBytes 0-1 land at 0x3E-0x3F, bytes 2-7 wrap to 0x30-0x35Write 2 bytes at 0x3E-0x3F, ACK poll until ACK, STOP
2STOP, then immediate readRead returns NACK or stale data, device still busyWrite remaining 6 bytes at 0x40-0x45, ACK poll until ACK
3Read back 0x30-0x450x30-0x35 hold the wrapped bytes, original data there is lostRead back matches the 8 bytes sent

On the real 24LC256 the page is 64 bytes, so the same wrap happens at 0x003E with a 64-byte write: only the last 2 bytes land where intended and the first 62 overwrite the start of that page.

Failure modes I check on the bench

Treating every NACK as an error and retrying the whole write immediately can restart the write cycle on some parts and extend the busy window indefinitely. The retry loop needs the timeout above and must distinguish the poll phase from the data phase. A read issued without ACK polling after STOP will NACK on the address byte, which looks like a wiring fault on a logic analyzer until you see the 5 ms gap. Power loss during the internal cycle leaves the page in an undefined state, so a config block that must survive it needs a CRC and a duplicate copy written in separate cycles, verified by readback after the poll succeeds. If ACK polling never succeeds, I check SDA/SCL pull-ups and whether another master or a stuck device is holding the bus, rather than increasing the timeout past the datasheet maximum by a large factor.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-42What must be set in the SPI flash status register before quad mode works, and what does the flash do if it is clear?

The 90-second answer

Set the QE bit, bit 6 of Status Register 1 on a W25Q style flash, before sending any quad opcode. With QE clear the part stays in single-bit mode and does not recognise quad commands such as 0x6B or 0xEB. The controller clocks out the opcode, the flash ignores it, and the read returns no valid data. That is why single-bit 0x03 reads work while quad reads return garbage or nothing.

QE is not a controller setting. It is stored in the flash itself, so it survives a controller reset and must be set after the part is first powered or after a status register write clears it. The usual bring-up sequence reads Status Register 1 with opcode 0x05, checks bit 6, and writes it back with opcode 0x01 if it is clear.

C
/* W25Q-style: enable quad mode, checked against the datasheet */
uint8_t sr1 = spi_flash_read_status1();   /* opcode 0x05, one byte back */
if ((sr1 & 0x40u) == 0u) {                /* QE is bit 6 */
    spi_flash_write_status1((uint8_t)(sr1 | 0x40u)); /* opcode 0x01 */
}
/* Only now send a quad opcode, for example 0x6B Quad Output Fast Read */
spi_flash_quad_read(0x6B, addr, buf, len);

Keep the other status bits unchanged when you write back. Status Register 1 also holds write-protect and block-protect bits, and writing a whole byte with those bits cleared can unprotect sectors you meant to keep locked. Read, modify only bit 6, write.

QE (SR1 bit 6)0x03 single-bit read0x6B quad readWhat the analyzer shows
0WorksIgnored, no valid dataOpcode clocked out, IO2 and IO3 stay idle
1WorksWorksData returned on IO0 to IO3

The check takes one analyzer capture. Decode the first byte after chip select falls. If it is 0x6B and the flash drives nothing on IO2 and IO3, read Status Register 1 next. A returned value with bit 6 clear confirms the cause. Set QE, repeat the same capture, and the quad data appears without any change to dummy cycles or clock rate.

No Yes Quad read returns no valid data Read SR1 with 0x05 QE bit 6 set? Write SR1 with QE set, retest Look elsewhere: dummy clocks, CS timing, clock rate

One caution on parts that differ. Some newer flashes use a separate quad enable bit in Status Register 2, or a non-volatile bit, instead of SR1 bit 6. The rule stays the same, check the datasheet status register map for the exact part on the board before writing. If QE is already set and quad still fails, QE was never the fault, and the next checks are the dummy clock count for the opcode and chip select held low for the full frame.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-43Walk me through implementing CRC-16 for a 64-byte frame sent over UART to a big-endian host, choosing polynomial, initial value, reflection and byte order, and proving the implementation is correct?

The 90-second answer

A CRC is not a polynomial alone. The wire format is the tuple (width, poly, init, refin, refout, xorout, check, residue) plus where the CRC sits and in which byte order it is sent. If any one differs, my receiver rejects frames from a correct peer. I fix the tuple in the protocol spec, implement it once in a testable function, and verify against the published check value for the ASCII string 123456789 before I touch the UART driver.

For a 64-byte frame on a Cortex-M0/M4, I would pick CRC-16/CCITT-FALSE if the host library already supports it: poly 0x1021, init 0xFFFF, refin false, refout false, xorout 0x0000, check 0x29B1. If the peer is a Modbus device, I would instead use CRC-16/MODBUS: poly 0x8005 reflected as 0xA001, init 0xFFFF, refin true, refout true, xorout 0x0000, check 0x4B37, and I would send the low byte first because Modbus defines that order. The polynomial choice follows the peer and the error model, not preference. Both detect all single and double bit errors in short frames and all burst errors up to 16 bits. For frames under 64 bytes the difference in Hamming distance is negligible, so interoperability decides.

Reflection is about bit order within each byte, byte order is about which CRC byte goes first. They are independent. A reflected algorithm shifts right and XORs with 0xA001. A non-reflected algorithm shifts left and XORs with 0x1021. Neither is dictated by host endianness. The CRC operates on the byte stream, so a big-endian host and a little-endian host compute the identical value from the same bytes. Endianness only matters when the host stores the received CRC in a uint16_t and extracts bytes from memory. If the host does (hi << 8) | lo, its endianness is irrelevant. If it does memcpy into a uint16_t, a little-endian host will interpret the wire bytes swapped and must byte swap. I state the wire order separately in the spec, for example crc_hi, crc_lo, and I test it by capturing the wire bytes.

C
/* CRC-16/CCITT-FALSE, non-reflected, checked on Cortex-M4 at -O2 */
#include <stdint.h>
#include <stddef.h>

static uint16_t crc16_ccitt_false(const uint8_t *data, size_t len)
{
    uint16_t crc = 0xFFFFu; /* init */
    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; /* xorout 0x0000 */
}

/* Transmit: append high byte first as the spec requires. */
uint16_t c = crc16_ccitt_false(frame, 64);
frame[64] = (uint8_t)(c >> 8);
frame[65] = (uint8_t)(c & 0xFFu);

The bitwise loop costs 8 iterations per byte, so 64 bytes is 512 shift and XOR steps. At roughly 6 to 8 cycles per bit step on a Cortex-M4 at 48 MHz, that is about 3,000 to 4,000 cycles, or 60 to 85 microseconds. That fits a 1 kHz loop, and it is small next to the UART time: 66 bytes at 115200 baud 8N1 is 660 bits, about 5.7 ms. On a Cortex-M0 at 16 MHz, or if the frame grows, I generate a 256 entry table at build time. The table costs 512 bytes of flash and drops the work to 64 lookups, roughly 300 cycles or 6 microseconds at 48 MHz. I do not hand type the table. I generate it from the same poly and reflection settings with a Python script and check the generated check value into version control.

ParameterCCITT-FALSEMODBUSWhy it matters
Poly0x10210x8005 / reflected 0xA001Determines which error patterns escape
Init0xFFFF0xFFFFMust match peer, changes check and residue
Refin / refoutfalse / falsetrue / trueShifts left vs right, bit order per byte
Xorout0x00000x0000Final inversion, often zero for these
Check for 1234567890x29B10x4B37The one number that proves the tuple
CRC byte order on wirehigh, lowlow, highIndependent of reflection and host endianness

Failure modes I test for

Loopback passing proves nothing. My transmitter and receiver can share the same wrong init and still agree. The check value catches that. I also run a residue test: append the CRC to the message and run the algorithm over the whole thing. For both variants above the residue is 0x0000 when the byte order matches the spec. If I swap the CRC bytes, the residue is non-zero and the receiver rejects a valid frame, which is exactly what I want to see in the test harness.

The second failure is coverage. I compute the CRC over the header, length, payload and sequence number, and I exclude the CRC field itself and any padding the DMA engine adds. If the length field is corrupted, the receiver must not trust it to find the CRC. I fix the frame size or put the length inside the covered region and validate it against the actual received byte count before checking the CRC. A receiver that searches for the CRC at a position derived from an unchecked length field will read past the buffer.

The third failure is a mismatch between the spec and the code after a refactor. I keep the parameters in one struct in the test code and generate both the C table and the Python reference from it. The unit test feeds 123456789, a 64 byte all-zero frame, and a frame with a single flipped bit in the last payload byte. The flipped bit must change the CRC and must be rejected. If a future change alters reflection, the check value test fails in CI before it reaches hardware.

Yes No Build frame: header + payload Compute CRC over covered bytes Append CRC hi then lo Transmit over UART Receiver collects fixed length Recompute CRC over covered bytes Matches received CRC? Accept frame Drop frame, count CRC error

On the receiver I count CRC errors separately from framing and overrun errors. A rising CRC error count with clean framing points at a parameter mismatch or a marginal signal integrity problem at higher baud rates. A rising count only on long frames points at the table generation or at a buffer overrun corrupting the tail. That split tells me whether to fix the spec, the wiring, or the driver, instead of guessing.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-44Walk me through implementing a ring buffer between a UART receive ISR and a task, covering head/tail indices, overflow handling, and memory barriers?

The 90-second answer

Use a single-producer, single-consumer ring buffer. The UART ISR is the only writer of head, the task is the only writer of tail, and neither side locks, blocks, or disables interrupts in the normal path. That ownership split is what makes it safe without a mutex.

Assume a Cortex-M, 8N1 UART, and a power-of-two buffer so wrap is a mask, not a division. The ISR writes the byte, issues a memory barrier, then publishes the new head. The task reads the byte, issues a barrier, then publishes the new tail. Full is next(head) == tail. Empty is head == tail. On overflow I drop the newest byte, increment a drop counter, and let the task detect the gap. For a command protocol that preserves framing better than overwriting the oldest bytes. For continuous telemetry, overwriting oldest is defensible, but then the task must know data was lost, so the counter is needed either way.

C
// Checked against C11, Cortex-M4, GCC/Clang intrinsics.
#include <stdint.h>
#include <stdbool.h>

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

typedef struct {
    uint8_t buf[RB_SIZE];
    volatile uint16_t head;    /* ISR writes, task reads */
    volatile uint16_t tail;    /* task writes, ISR reads */
    volatile uint32_t dropped; /* ISR writes, task reads */
} ring_t;

static ring_t rx;

/* Called from UART RX ISR. Never blocks. */
bool rx_push_isr(uint8_t byte)
{
    uint16_t head = rx.head;
    uint16_t next = (uint16_t)((head + 1u) & RB_MASK);

    if (next == rx.tail) {
        rx.dropped++;
        return false;
    }
    rx.buf[head] = byte;
    __DMB();          /* data visible before head moves */
    rx.head = next;
    return true;
}

/* Called from task context. Returns false when empty. */
bool rx_pop_task(uint8_t *byte)
{
    uint16_t tail = rx.tail;

    if (tail == rx.head) {
        return false;
    }
    *byte = rx.buf[tail];
    __DMB();          /* byte consumed before tail moves */
    rx.tail = (uint16_t)((tail + 1u) & RB_MASK);
    return true;
}

Why the barrier, and why volatile alone is not enough

volatile stops the compiler caching head or reordering accesses to that object in a way that changes observable behaviour. It does not order the buffer store against the index store, and it does not order anything at the hardware level. Cortex-M is weakly ordered, and the compiler can also move the index update ahead of the data write if it thinks no aliasing occurs.

The sequence that matters is: store byte, barrier, store head. Without the barrier the task can see the new head, read a stale byte, and the ISR can later overwrite that slot thinking the task already consumed it. The mirror sequence in the task, read byte, barrier, store tail, stops the ISR reusing the slot before the read completes. __DMB() is the barrier to use here. __DSB() waits for completion of the access itself, which is stronger than needed for ordering and costs more. On a Cortex-M0/M3/M4 the compiler barrier alone is often enough in practice, but the explicit DMB documents the requirement and survives a port to a weakly ordered core or a compiler that reorders aggressively.

uint16_t indices are also a deliberate choice. An aligned 16-bit load or store is single-copy atomic on Cortex-M, so the task never reads a torn head. A 32-bit index would also be atomic on that core, but a 64-bit counter or a struct update would not be.

Worked trace, size 8 for readability

StepActorheadtailActionResult
1ISR0 to 10push Abuffer [A]
2ISR1 to 20push Bbuffer [A,B]
3Task20 to 1popreturns A
4ISR2 to 31push Cbuffer [B,C]
5Task31 to 2popreturns B
6Task32 to 3popreturns C, now empty

Full check with size 8: if head is 7 and tail is 0, next(head) is 0, which equals tail, so the buffer holds 7 bytes and the next push is dropped. Keeping one slot empty is what distinguishes full from empty when both indices are equal.

Sizing and failure modes

At 115200 baud 8N1 the wire carries about 11520 bytes per second, so one byte arrives every 87 microseconds. A task that runs every 10 ms can miss about 115 bytes in that window, which is why 256 bytes is a sane starting size and 64 bytes is not. Size for worst-case task latency plus interrupt latency, not average latency. If the task is starved by a higher priority loop, the drop counter climbs and the ISR still returns quickly. That is detectable in the field: log dropped delta per second and raise it as a fault when it is non-zero, because silent loss corrupts frames.

Two failure modes to name in an interview. First, the ISR itself overruns the hardware FIFO because the ISR is too long or a higher priority interrupt blocks it. The ring buffer cannot fix that, so keep the ISR to the push plus the UART status clear, and check the UART overrun flag separately. Second, a second writer appears, for example DMA or a second UART sharing the buffer. The lock-free argument collapses, and the fix is a separate buffer per producer or a critical section, not a barrier.

byte then DMB then head tail then DMB then byte full UART RX interrupt rx_push_isr ring buffer Task rx_pop_task dropped counter

Initialisation needs interrupts disabled around the first setup of head and tail, since that is the one place both sides could race. After that, no critical section is needed in push or pop.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-45In FreeRTOS, when would you use a queue, a binary semaphore, a counting semaphore or a mutex, and how do ownership and blocking behaviour differ?

The 90-second answer

I would pick by what is being transferred. A queue transfers data by copy, so I use it when a producer and consumer need to pass a struct, a pointer with a defined lifetime, or a message. A binary semaphore transfers a single event with no data, so I use it to signal that something happened, typically from an ISR to a task. A counting semaphore transfers a count, so I use it for a pool of identical resources or to count events that can accumulate. A mutex transfers exclusive ownership of a shared resource, so I use it to protect a non-reentrant driver or a shared data structure. Only the mutex has ownership and priority inheritance. The other three can be given by a task that did not take them, which is exactly why they work for signalling and exactly why they are unsafe for mutual exclusion.

PrimitiveWhat movesWho may giveBlocking behaviourPriority inheritance
QueueData, copied into queue storageAny task or ISR that sendsSend blocks when full, receive blocks when empty, both with a timeoutNo
Binary semaphoreOne token, no dataAny task or ISRTake blocks until token present or timeoutNo
Counting semaphoreUp to N tokensAny task or ISRTake blocks until count is above zero or timeoutNo
MutexExclusive ownershipOnly the task that took itTake blocks until free or timeout, give releases itYes, in FreeRTOS

Ownership and the failure it prevents

A mutex in FreeRTOS is created with xSemaphoreCreateMutex() and taken with xSemaphoreTake(). The kernel records the holder. If a high priority task blocks on that mutex, the holder temporarily inherits the high priority task's priority until it gives the mutex back. That bounds priority inversion to the holder's critical section. A semaphore has no holder record. Any task can give it, so a low priority task that happens to give a binary semaphore does not inherit anything, and a high priority task waiting on it can be delayed by unrelated work.

That difference decides the ISR case. An ISR can give a semaphore or send to a queue with the FromISR variant, and it can never take a mutex or block. Signalling with a binary semaphore from a GPIO ISR to a task that reads the sensor is idiomatic. Protecting the I2C bus with that same semaphore is a bug: a second task can give the semaphore while the first task is mid transaction, both tasks enter the critical section, and the bus corrupts. The same bug appears if a queue of length one is used as a lock. The copy semantics hide the ownership problem until two tasks interleave.

C
/* FreeRTOS 11.x, Cortex-M4, checked against the FreeRTOS kernel API */
static QueueHandle_t sensorQ;
static SemaphoreHandle_t i2cMutex;
static SemaphoreHandle_t dataReady; /* binary semaphore */

void sensor_isr(void) {
    BaseType_t woken = pdFALSE;
    xSemaphoreGiveFromISR(dataReady, &woken);
    portYIELD_FROM_ISR(woken);
}

void sensor_task(void *arg) {
    sensor_t sample;
    for (;;) {
        xSemaphoreTake(dataReady, portMAX_DELAY);
        read_sensor(&sample);              /* ISR already captured raw data */
        xQueueSend(sensorQ, &sample, portMAX_DELAY); /* copy, blocks if full */
    }
}

void i2c_task(void *arg) {
    for (;;) {
        xSemaphoreTake(i2cMutex, portMAX_DELAY); /* owned, inherits priority */
        i2c_write(reg, buf, len);
        xSemaphoreGive(i2cMutex);
        vTaskDelay(pdMS_TO_TICKS(10));
    }
}

Note the queue send in sensor_task blocks when the queue is full. That is backpressure, and it is a feature when the consumer is slower than the producer. It becomes a failure mode when the producer is an ISR, because the FromISR send cannot block and returns errQUEUE_FULL. The ISR must drop, overwrite, or count the loss explicitly. A counting semaphore has the same saturation behaviour: give it when the count is already at its maximum and the give fails silently unless the return value is checked.

Worked trace: inheritance versus semaphore

Assume a low priority task L holds a shared buffer, a medium priority task M is runnable, and a high priority task H needs the buffer.

StepWith mutexWith binary semaphore
L takes the primitiveL owns it, runs at low priorityL takes token, no ownership recorded
H blocks on itH blocks, L inherits H priorityH blocks, L stays low priority
M becomes runnableM cannot preempt L, because L now runs at H priorityM preempts L and runs to completion
L finishes and releasesL drops back to low priority, H runsH waits until M and any other medium work finish

With the semaphore, H's delay is unbounded in the worst case, because it depends on work that has nothing to do with the buffer. With the mutex, H waits only for L's critical section, which is the bound I can put in a timing analysis.

When not to use each one

I would not use a mutex to signal an ISR, because the ISR cannot take it and the semantics are backwards. I would not use a semaphore to protect a shared resource, because nothing stops a third task from giving it. I would not use a queue to pass a large buffer by value every millisecond if a pointer plus a semaphore would do, because the copy costs cycles and stack traffic on a small MCU. I would not use a counting semaphore with a count of one and call it a mutex, because I lose inheritance and gain nothing. The queue is the only one of the four that moves data, the mutex is the only one that has an owner, and the two semaphores are the right tools when the only thing that matters is that an event happened, once or N times.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-46What lock ordering rule prevents two tasks from deadlocking when both need the same two mutexes?

The 90-second answer

Acquire the mutexes in the same global order in every task. If both tasks need mutex A and mutex B, both take A first and B second. That single rule prevents deadlock between them.

Deadlock in this case is a circular wait. Task 1 holds A and waits for B. Task 2 holds B and waits for A. Neither task can release what it holds because it is blocked waiting for the other. A consistent order makes that cycle impossible. A task that holds A may wait for B, but no task ever holds B while waiting for A, so the wait graph cannot loop.

C
/* Bad: opposite orders */
void task_one(void)
{
    xSemaphoreTake(mutex_a, portMAX_DELAY);
    xSemaphoreTake(mutex_b, portMAX_DELAY); /* waits here */
    xSemaphoreGive(mutex_b);
    xSemaphoreGive(mutex_a);
}

void task_two(void)
{
    xSemaphoreTake(mutex_b, portMAX_DELAY);
    xSemaphoreTake(mutex_a, portMAX_DELAY); /* waits here */
    xSemaphoreGive(mutex_a);
    xSemaphoreGive(mutex_b);
}
StepTask oneTask twoResult
1Takes mutex AHolds A
2Takes mutex BHolds B
3Waits for mutex BWaits for mutex ACircular wait
C
/* Fixed: one documented order, A before B everywhere */
void task_one(void)
{
    xSemaphoreTake(mutex_a, portMAX_DELAY);
    xSemaphoreTake(mutex_b, portMAX_DELAY);
    xSemaphoreGive(mutex_b);
    xSemaphoreGive(mutex_a);
}

void task_two(void)
{
    xSemaphoreTake(mutex_a, portMAX_DELAY);
    xSemaphoreTake(mutex_b, portMAX_DELAY);
    xSemaphoreGive(mutex_b);
    xSemaphoreGive(mutex_a);
}

Now if task one holds A and task two is waiting for A, task two holds nothing. Task one can take B, finish its work, and release both. Task two then runs. The second task waits, but it does not deadlock.

Take mutex A first Take mutex B second Do work Release B then A

I write the order beside the mutex definitions, for example /* Order: queue_mtx before tx_mtx. Never take tx_mtx first. */, and I check every take site against it. The rule covers error paths too. A task that takes A, fails a check, and then takes B in a cleanup path has broken the order just as surely as the main path.

Lock ordering does not fix priority inversion. That is a separate problem where a low priority holder delays a high priority waiter while a medium priority task runs. Priority inheritance addresses that case by raising the holder. Ordering addresses deadlock. A design can need both, and using a mutex with inheritance does not remove the need for a fixed order.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-47How do you size an RTOS task stack from worst-case call depth, interrupt preemption and printf, and detect overflow in production?

The 90-second answer

Size from the deepest call path, not from average use. Add the frames and locals on that path, add the largest library call on it (usually printf or a floating point helper), add interrupt nesting if the RTOS shares the task stack, then add a margin and prove it with painting. On Cortex-M with FreeRTOS, an ISR that preempts a task runs on that task's stack (PSP), so the ISR frame and anything it calls must fit inside the task allocation. That is the part people miss when they size only for the task itself.

Worked sizing

Take a hypothetical 32-bit Cortex-M4 task at -O2. Hypothetical frame sizes, measured with -fstack-usage and checked in the map file, are labelled as such here.

PathCost (bytes)
sensor_task frame + locals48
parse_frame frame + locals96
crc32 frame + locals32
snprintf worst path (format, varargs, float conversion)512
ISR preempting at deepest point: hardware frame 32 + ISR locals 40 + HAL_UART_IRQHandler 64136
Alignment, saved registers not in frames, RTOS context32
Total worst case856

Round up to a word multiple and add margin for compiler variation and a deeper error path: 856 bytes becomes 1024 bytes. If the error path calls printf with %f on a Cortex-M0 without an FPU, that 512 byte figure can double. Measure it, do not guess it. -fstack-usage gives static frames per function. It does not give you varargs expansion, recursion, or library internals, so add those by measurement on the target.

Two rules keep the arithmetic honest. First, recursion and variable length arrays make the worst case unbounded or compiler dependent, so ban them in that task or bound them explicitly. Second, a function pointer call has no static frame. If the deepest path goes through a callback, size for the largest callback that can be registered there.

Detecting overflow

Paint the stack at creation, check it in the hook, and read the high water mark in test.

C
// FreeRTOSConfig.h (FreeRTOS 11.x)
#define configCHECK_FOR_STACK_OVERFLOW 2
#define configUSE_MALLOC_FAILED_HOOK 1

void vApplicationStackOverflowHook(TaskHandle_t xTask, char *pcTaskName)
{
    (void)xTask;
    // Log pcTaskName and the faulting task's stack pointer to a
    // reserved RAM region. Do not call printf here: the stack is
    // already suspect and printf may be what overflowed it.
    log_fault_to_ram("STACK_OVERFLOW", pcTaskName);
    configASSERT(0);
}

configCHECK_FOR_STACK_OVERFLOW 1 checks the last few words on a context switch. 2 also checks the stack pointer against the end of the stack on each switch. Neither catches a transient overflow that returns before the switch, which is exactly what a deep printf call does. Painting catches that case in test.

C
void paint_stack(StackType_t *pucStack, size_t uxDepth)
{
    for (size_t i = 0; i < uxDepth; i++) pucStack[i] = 0xA5A5A5A5;
}

// After a soak test:
UBaseType_t free_words = uxTaskGetStackHighWaterMark(task_handle);
// free_words * sizeof(StackType_t) is the minimum untouched tail.
// If it is under ~15% of the allocation, grow the stack or cut printf.

uxTaskGetStackHighWaterMark returns the smallest free space seen since creation, counted from the painted pattern. Run the soak with interrupts at full rate, the error paths forced, and the longest log line emitted. A mark that looks fine in idle testing and collapses under a fault storm is a stack bug that ships.

Failure modes to name

A stack overflow on Cortex-M usually corrupts the adjacent heap block or the next task's stack, so the crash appears in an unrelated task. The hook fires late or not at all if the overflow overwrites the TCB. That is why the hook logs to fixed RAM and halts, rather than trying to recover.

printf deserves its own line in the budget. Newlib printf with %f pulls in floating point formatting and a large buffer on the stack. On a small MCU, route diagnostics through a fixed buffer and snprintf with integer formats only, or send the string over UART from a dedicated logging task with its own large stack. Measure the logging task separately. Do not let a debug print in a 256 byte control task become the deepest call in the system.

If the high water mark is tight, the fix order is: remove printf from the path, shrink locals (large buffers belong in static storage, not on the stack), then grow the stack. Growing first hides the real cost and leaves the next task undersized.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-48How would you implement tickless idle and peripheral clock gating on a battery-powered Cortex-M device to hit a 5 µA sleep target without missing a 10 ms sensor wake deadline?

The 90-second answer

Assume a Cortex-M4 at 80 MHz, a 1 kHz RTOS tick, a sensor that must be serviced within 10 ms of its data-ready interrupt, and a sleep budget of 5 µA measured at the battery. Tickless idle means the periodic SysTick stops being a wake source. The idle hook finds the earliest deadline among delayed tasks, timers and known peripheral events, programs a one-shot wake timer for that instant, gates every peripheral clock the task set does not need, then executes WFI. Peripheral clock gating is separate: a peripheral whose RCC enable bit stays set keeps its bus clock domain, its synchronisers and often its regulator domain alive, even if the peripheral itself is idle.

The failure I see most often is gating clocks in the wrong order. You stop the SysTick, gate UART, SPI, ADC and timers, enter sleep, and then discover the sensor interrupt cannot wake the part because its clock domain was gated, or the wake timer was programmed from a clock that stops in Stop mode. The fix is to treat wake sources as a contract: every wake source names the clock it needs, the latency to restore that clock, and the deadline it protects.

Tickless idle, concretely

In FreeRTOS this is configUSE_TICKLESS_IDLE with vApplicationIdleHook or the port's preSleep/postSleep hooks. In bare metal the same logic sits in the main loop. The sequence is:

  1. Suspend the scheduler or mask interrupts briefly while you compute the next wake time.
  2. Take the minimum of xTaskGetTickCount deadlines, software timer expiry, and any hardware event you can predict, such as a UART baud window or a sensor conversion time.
  3. If that minimum is sooner than the tick period, do not sleep. You would wake, reprogram, and sleep again for no gain.
  4. Program a one-shot timer on a clock that survives the chosen sleep mode, for example LPTIM on LSE or the RTC on STM32L4 Stop modes. SysTick itself stops in Stop, so it cannot be the wake timer there.
  5. Gate peripheral clocks, set the sleep mode, clear the pending flag for the wake source, then WFI.
  6. On wake, restore clocks first, then correct the tick count by the elapsed time before unblocking tasks.
C
/* Checked against FreeRTOS 11 tickless idle hooks, Cortex-M4 port */
void vApplicationIdleHook(void)
{
    uint32_t nextWakeTicks = next_deadline_ticks(); /* tasks + timers */
    if (nextWakeTicks < 2) return;                  /* too soon to sleep */

    vTaskSuspendAll();
    nextWakeTicks = next_deadline_ticks();
    if (nextWakeTicks >= 2) {
        lptim_program_oneshot(nextWakeTicks * tick_us());
        gate_unused_peripheral_clocks();            /* RCC AHBENR/APBENR */
        enter_stop_mode();                          /* sets SLEEPDEEP, WFI */
        restore_clocks();
        correct_tick_count(lptim_elapsed_us());
    }
    vTaskResumeAll();
}

The vTaskSuspendAll window matters. Without it a task can unblock, move its deadline earlier, and you sleep past it. Keep the window short and never call a blocking driver inside it.

Why the tick alone breaks the budget

Hypothetical but typical figures for this class of part: active current 12 mA at 80 MHz, Stop current 2.5 µA, sensor wake every 10 s for 50 ms.

CaseArithmeticAverage current
Sleep only, no tick2.5 µA x 0.995 + 12 mA x 0.005about 63 µA
SysTick wake every 1 ms, 30 µs awake each time12 mA x 0.03360 µA added
Tickless, one wake per sensor cyclewake overhead amortised over 10 sunder 5 µA added

A 1 kHz tick that wakes the core for even 30 µs costs more than the entire sleep budget. That is the whole argument for tickless idle on a battery part. It also explains why measuring sleep current with the tick running tells you nothing about the gated design.

Clock gating audit

Gate by domain, not by peripheral name. On STM32L4 the RCC enable registers are RCC_AHB1ENR, RCC_AHB2ENR and RCC_APB1ENR/RCC_APB2ENR. Clearing a bit stops the clock to that peripheral. Some peripherals share a domain with a wake source, so check the reference manual's clock tree before clearing.

PeripheralGating action in sleepWake implication
UART, SPI, I2CClear enable bit, deinit DMACannot wake from RX. Use EXTI on the RX pin or a wakeup-capable UART instead.
ADCClear enable bit, stop DMAConversion must restart after wake. Add 20 to 50 µs trigger latency to the deadline budget.
General timersClear enable bit, keep LPTIM/RTC runningPWM and capture stop. Do not gate a timer that generates a wake edge.
GPIO, RCC, PWR, EXTINever gateThese are the wake path. Gating them removes the interrupt that was supposed to wake you.

Two details bite in practice. First, some peripherals need a software reset or a clock pulse after the enable bit is set again before their registers accept writes. Second, DMA channels keep running if their peripheral clock is gated mid-transfer. Quiesce DMA, wait for the transfer-complete flag, then gate.

Protecting the 10 ms deadline

Yes No Idle hook entered Compute earliest deadline Deadline under 2 ticks? Stay awake, run scheduler Program LPTIM one-shot Gate unused clocks Enter Stop, WFI Wake: restore clocks Correct tick, resume scheduler Service sensor ISR within budget

Budget the wake path end to end: wake latency from Stop (about 5 to 10 µs on STM32L4 at 80 MHz after clock restore), EXTI entry, sensor ISR, and the I2C or SPI read. If that total is 400 µs, a 10 ms deadline has margin. If the sensor needs its own clock domain restored through a PLL relock, that can add 200 µs to 1 ms. Measure it with a GPIO toggled on wake entry and on ISR entry, captured on a scope, with the debugger detached. A debugger attached often holds clocks open and hides the fault.

Verification

Measure three numbers separately: Stop current with all clocks gated and no wake timer, average current over a full 10 s sensor cycle, and worst-case wake-to-ISR latency. Log the programmed wake time and the actual wake time in RAM and compare them over a thousand cycles. Drift between the two means the one-shot timer runs from a different clock than the tick correction assumes. If sleep current is right but the deadline slips, the usual cause is a gated clock on the wake path or a tick correction that rounds down and releases a task late.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-49Your 3.3 V rail sags under load and the MCU keeps resetting in a loop: how do you detect the reset cause, distinguish brownout from other resets, and set thresholds and hysteresis to stop the loop?

The 90-second answer

Read the reset-cause flags first, before anything clears them, and treat a brownout differently from a watchdog or a software reset. On STM32F4, that is RCC->CSR: PORRSTF, PINRSTF, SFTRSTF, IWDGRSTF, WWDGRSTF, LPWRRSTF, plus the PVD flag in PWR->CSR. Log the cause and a brownout counter to a backup register, then clear the flags with RMVF. If the last reset was a POR or PVD/BOR event, do not immediately re-enable the load that caused the sag. Hold peripherals off until the rail has stayed above the rising threshold for a fixed interval, and after repeated brownouts in a short window, boot into a safe state with the load disabled.

The loop usually looks like this: rail sags to 2.85 V, MCU resets, load disappears, rail recovers to 3.3 V, firmware boots, load turns on, rail sags again. Hysteresis alone does not fix that if the load is the cause. You need three things together: a falling threshold that warns early, a rising threshold that is meaningfully higher, and a boot policy that refuses to reapply the load until the supply has proven itself and the fault count is low.

Thresholds and hysteresis, with real numbers

Assume a 3.3 V rail, a buck or LDO with 100 mV ripple plus load transient, and an MCU whose BOR can be set to 2.70 V. A workable starting point, to be checked against the specific datasheet tables for PVD levels:

ThresholdValuePurpose
PVD falling2.90 VInterrupt while the core still runs. Stop DMA, flush state, save a fault record.
PVD rising3.05 VRail considered good again. 150 mV of hysteresis, well above 100 mV ripple.
BOR level2.70 VHardware reset if the rail falls further. Last resort, not the normal detector.
Stable time50 msRail must stay above 3.05 V for 50 ms before the load is enabled.

The 150 mV band matters. If falling and rising thresholds were both 2.90 V, ripple around the threshold would toggle the PVD interrupt and the enable logic. With 150 mV of separation, a 100 mV transient cannot cross both edges. The 50 ms stable time covers the buck converter settling after the load step and stops a fast boot, sag, reboot cycle from repeating every few milliseconds.

Detecting and recording the cause

C
/* STM32F4, checked against RM0368 RCC and PWR register maps */
#include "stm32f4xx.h"

typedef enum { RESET_UNKNOWN, RESET_POR, RESET_PIN, RESET_SOFTWARE,
               RESET_IWDG, RESET_WWDG, RESET_LOW_POWER,
               RESET_BROWNOUT } reset_cause_t;

reset_cause_t read_reset_cause(void)
{
    uint32_t csr = RCC->CSR;
    reset_cause_t cause = RESET_UNKNOWN;

    if (csr & RCC_CSR_PORRSTF)      cause = RESET_POR;
    if (csr & RCC_CSR_PINRSTF)      cause = RESET_PIN;
    if (csr & RCC_CSR_SFTRSTF)      cause = RESET_SOFTWARE;
    if (csr & RCC_CSR_IWDGRSTF)     cause = RESET_IWDG;
    if (csr & RCC_CSR_WWDGRSTF)     cause = RESET_WWDG;
    if (csr & RCC_CSR_LPWRRSTF)     cause = RESET_LOW_POWER;
    if (PWR->CSR & PWR_CSR_PVDO)    cause = RESET_BROWNOUT; /* PVD was active */

    RCC->CSR |= RCC_CSR_RMVF; /* clear all reset flags */
    return cause;
}

Two traps here. First, PVDO only tells you the PVD output state at read time, so a rail that recovered during boot can hide the brownout. Capture it in the PVD interrupt handler into a backup register before the reset, and also treat a POR flag with a non-zero brownout counter as suspect. Second, many HAL init routines clear these flags. Read the cause in SystemInit or the first lines of main, before clock and peripheral init.

For retention, use the backup domain (RTC->BKP0DR and neighbours, powered by VBAT) or retained SRAM such as SRAM2 on STM32H7 parts. Store a magic word, the last cause, a brownout counter, and a timestamp or boot counter. Backup registers survive Stop and Standby on most STM32 parts but are cleared by a true VBAT loss, so validate the magic and a simple checksum before trusting the counter. Increment the brownout counter only after the rail has been stable for the 50 ms window, otherwise a single sag that bounces the reset pin several times inflates the count.

Boot policy that breaks the loop

No Yes No Yes Yes No Read reset cause Cause is brownout or POR? Normal boot Load enable stays off Wait for rail above rising threshold Rail stable 50 ms? Brownout count in last 10 min >= 3? Safe mode: load off, log fault, wait for service Enable load, clear counter after 60 s clean run

The PVD interrupt handler should do the minimum: set a flag, stop the load enable GPIO, and record the event. Do not do logging or flash writes in that handler, because the rail may collapse before they finish. A flash write during a sag is a common way to corrupt the very fault record you wanted.

Failure modes to name in the interview: a supervisor IC with its own fixed threshold that disagrees with the MCU BOR, so the supervisor resets first and the MCU never sees a PVD event; a load enable that defaults on through a pull-up before firmware runs, so the sag happens before your code executes; and a battery whose internal resistance rises as it discharges, which moves the sag point over the product life. The fix for the second one is hardware: pull the enable down, and let firmware raise it only after the stable check passes.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-50When are boot-mode strapping pins sampled by a chip, and what does that mean for measuring them on a first-spin board?

The 90-second answer

Strapping pins are sampled once, at reset release. The chip latches the boot mode in that sampling window and ignores the pins afterwards. So on a first-spin board you measure the pins while reset is still asserted, not after the chip has booted. A pin that reads correctly after boot can still have been sampled wrong.

That one rule decides the whole check. Hold the part in reset, power the board, measure each strapping pin against its expected high or low level, then release reset and read back what the chip latched.

What to measure

A strapping pin is usually tied to a supply rail or ground through a pull resistor, often 10 kΩ. With a 10 kΩ pull-up to 3.3 V and no other load, the pin sits at 3.3 V and the chip samples a logic high. With a 10 kΩ pull-down to ground, it sits at 0 V and the chip samples a logic low. If another device loads the pin, the level is a divider. For example, a 10 kΩ pull-up with a 100 kΩ path to ground gives 3.3 V × 100 / 110, about 3.0 V, still a clear high for a typical CMOS input. A level near mid-rail, about 1.65 V on a 3.3 V supply, is ambiguous and can sample either way.

Measure during reset with a multimeter or scope. Compare the reading to the schematic intent for that pin. Then release reset and check the latched value if the chip exposes one:

C
/* Read the boot mode the chip latched at reset release */
uint32_t strap = BOOT_CFG->STRAP_STATUS;
uint32_t mode  = (strap >> BOOT_CFG_MODE_SHIFT) & 0x7u;
/* mode must match the pin levels measured while reset was asserted */

If the latched mode disagrees with the pin level you measured during reset, the pin moved after the sampling edge. If it agrees with the pin level after boot but not during reset, you measured too late.

Timing trace

Power applied, reset asserted Measure strapping pins Reset released, chip samples pins Chip boots in latched mode Read STRAP_STATUS register
StageReset pinStrapping pinWhat you check
Power on, reset heldLowHigh or low per schematicPin level matches pull resistor
Reset releaseLow to highMust be stable at that momentChip samples the level now
After bootHighMay change, chip ignores itLatched mode in register

Isolating a mis-strapped part

If a pin reads wrong during reset, power off and measure the pin to ground and to its rail. A 10 kΩ pull-up should read about 10 kΩ to the rail. Near 0 Ω points to a solder bridge or short. A very high reading points to a missing or wrong resistor. If the unpowered reading is correct but the powered reading during reset is wrong, another device is driving the pin. Lift the chip pin or remove the pull resistor. If the pin then reads correctly, the fault is on the board. If it still reads wrong, suspect the chip or a shared load on that pin.

Firmware cannot fix a wrong sample. The mode is already latched before the first instruction runs, so the correction is a resistor, solder or layout change.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-51Walk me through how you would verify power sequencing, absolute maximum ratings, and reset timing from a datasheet and schematic before first power-on?

The 90-second answer

I treat the datasheet as a contract and the schematic as a claim about that contract. Before power-on I build a one-page table with four columns: requirement, source page or table, where the schematic implements it, and how I will measure it on the bench. If a row has no measurement, it is not verified.

For power sequencing I extract every rail, its order, minimum separation, ramp limits and which rails must be present before reset releases. For absolute maximum ratings I list every pin voltage, current and temperature limit, then check the worst case the schematic can produce, including start-up transients and a rail that is present while another is absent. For reset I pull the POR threshold, reset pulse width, hold time after the last rail is stable, and any requirement that a clock or a specific rail be valid before reset deasserts. Then I measure all of it with a scope on first power-on, current limited, before code runs.

No Yes Extract rails, order, limits from datasheet Map each rail and reset net on schematic Worst-case check: abs max, backpowering, overshoot Bench: current-limited supply, scope on rails and reset Sequence and timing pass? Fix schematic or supervisor, repeat Release reset, run firmware bring-up

Sequencing and absolute maximum ratings

A typical failure is not a rail being wrong in steady state. It is a rail arriving early through a pull-up, an ESD diode or a shared enable. Example, labelled as a worked example: a 3.3 V MCU rail, a 1.2 V core rail and a sensor at 3.3 V. The datasheet says core must not exceed I/O by more than 0.3 V, I/O absolute maximum is 3.6 V, and reset must stay asserted until 10 ms after both rails are in regulation. On the schematic the sensor enable is tied to 3.3 V through a MOSFET, but the I2C pull-ups go to a separate always-on 3.3 V. If the MCU rail ramps 40 ms after the sensor rail, the pull-ups backpower the MCU through its I2C pins. The MCU may sit at 1.8 V, below its POR threshold, with no reset asserted. That is a sequencing violation even though both rails eventually read 3.3 V.

I check each pin group against the absolute maximum table, not just VDD. That includes analog inputs, BOOT pins, debug pins and any pin connected to a rail that can be present alone. I also check current limits: input clamp current, total current per rail, and LDO dropout at the load current the schematic implies. A 3.3 V LDO fed from 5 V with 500 mA load and a 1.5 V dropout needs 4.8 V minimum at the input under load and temperature. If the upstream 5 V rail can droop to 4.6 V, the LDO drops out and the MCU rail follows the input down. The datasheet limit is met on paper and missed in the corner.

CheckDatasheet sourceSchematic checkBench measurement
Rail order and separationPower sequencing diagram, timing tableEnable chain, supervisor inputs, MOSFET gatesScope: all rails, 10 ms/div, trigger on first rail
Absolute maximum per pinAbsolute maximum ratings tablePull-ups, dividers, level shifters, backpower pathsScope at pin, worst-case rail combination
Ramp and overshootRecommended operating conditions, LDO noteCapacitor values, LDO stability, hot-swap pathScope at load, cold start and hot plug
Reset threshold and holdPOR, reset timing, supervisor specSupervisor threshold, RC delay, reset net routingScope: reset vs last rail crossing threshold
Clock before reset releaseReset and clock chapterCrystal load, PLL lock, clock monitorScope or GPIO trace from early firmware

Reset hold time, with numbers

Reset hold is where schematics quietly fail. Suppose the supervisor releases reset 200 ms after the 3.3 V rail crosses 3.0 V, and the MCU needs reset held 10 ms after VDD reaches 3.0 V. That looks safe. Now add the RC on the reset net: 100 kΩ and 100 nF gives a time constant of 10 ms. The supervisor output may release in 200 ms, but the MCU pin sees a slow ramp. If the MCU reset input has a threshold of 1.0 V and no hysteresis specified, it can chatter or release while the rail is still rising. I measure reset at the MCU pin, not at the supervisor output, and I measure the time from the last rail crossing its minimum operating voltage to reset crossing the MCU threshold.

A second calculation catches divider errors before the bench. If firmware senses a 12 V rail through 100 kΩ over 10 kΩ to a 3.3 V ADC, the nominal ADC voltage is 12 × 10/110 = 1.09 V. With 1% resistors the worst case is about 1.11 V, fine. If the same divider feeds a digital input with a 3.6 V absolute maximum and the 12 V rail can overshoot to 20 V during load dump, the pin sees 1.82 V, still fine, but the resistor dissipation and the fault case where the 10 kΩ goes open put 20 V on the pin. That open-resistor case is the one that kills parts, and it only appears if I ask what happens when a single component fails.

What I do on the bench

First power-on is current limited to a value just above expected inrush, with the scope probing every rail, reset and the enables. I trigger on the first rail and capture the order. I repeat with the supply ramped slowly, because a bench supply that ramps in 1 ms hides a problem that a battery or a slow upstream converter exposes in 100 ms. I also pull each rail in turn, where the design allows it, to see backpowering: if a rail sits above 0.3 V with its supply removed, something is feeding it.

If a check fails, the fix is usually in the schematic, not in firmware. Firmware cannot repair a rail that arrives 40 ms late or a pin that exceeds its absolute maximum during ramp. I would move the pull-ups to the sequenced rail, add a supervisor input for the missing rail, or hold reset with a dedicated circuit until all rails are proven. Only after the scope shows the sequence, the reset hold and the pin voltages inside limits do I release reset and let firmware run.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-52Your SPI clock at 50 MHz shows ringing and overshoot on the scope and flash reads corrupt intermittently: how do you diagnose it and fix it with termination and drive strength?

The 90-second answer

Ringing on a fast SPI clock is a reflection problem, not a firmware timing problem. The driver launches an edge into a trace whose impedance is not matched at the far end. The wave reflects, returns, and bounces again. On the scope you see overshoot past the supply, undershoot below ground, and sometimes a second crossing of the receiver threshold. That second crossing can clock in a false bit or make the flash sample data on the wrong edge.

I would first prove it is signal integrity and not mode or chip-select timing. I would probe at the receiver pin with a short ground spring, not a 10 cm clip lead, because the clip lead itself rings. I would record SCLK and MOSI at the flash pin at the failing clock rate, then drop the rate by half. If the ringing amplitude stays roughly the same in volts but the errors disappear, and if the waveform shows overshoot beyond VDD or below ground, that points to reflections. A logic analyzer will show clean digital edges and hide this completely.

Then I would fix the edge at the source with series termination, and only add parallel termination if the topology needs it. For a point-to-point SPI bus to one flash, series termination is the default. A 22 to 33 ohm resistor placed close to the MCU pin absorbs the returning reflection. Lower drive strength or slower slew rate on the GPIO is the second knob. It reduces the energy in the edge, at the cost of a slower rise time.

Why the trace rings: a worked example

Assume a hypothetical but typical board: FR4 trace, 12 cm long, driver rise time 1 ns, 50 MHz SPI clock (20 ns period, 10 ns half period).

Propagation velocity on FR4 is about 15 cm/ns, so delay per centimetre is 1/15 ns = 0.067 ns/cm. One-way delay for 12 cm is 12 x 0.067 = 0.8 ns. Round trip is 1.6 ns. As a rule of thumb, a trace stops being electrically short near Lcrit = rise time / (6 x delay per cm). That gives 1 ns / (6 x 0.067 ns/cm) = 2.5 cm. At 12 cm the trace is almost five times that length, so reflections overlap the edge and are visible. The factor of six is a rule of thumb, not a specification limit.

The table below is illustrative, with hypothetical figures for this example board, not measured data from a specific product.

Measurement at flash pin, illustrative50 MHz, full drive25 MHz, full drive50 MHz, series 27 ohm + low slew
SCLK overshoot above 3.3 V rail+0.9 V+0.85 V+0.25 V
SCLK undershoot below ground-0.7 V-0.65 V-0.15 V
10-90% rise time1.0 ns1.0 ns1.8 ns
Flash read errors per 1e6 frames340000

The middle column is the diagnostic. Halving the clock does not change the ringing amplitude, because the edge rate did not change. It only gives the ringing time to settle before the next sampling edge. The right column shows the fix working: rise time grows, ringing shrinks, and the receiver still sees a valid edge well inside its setup window.

No Yes Yes Errors at high SPI clock Probe SCLK and MOSI at receiver with ground spring Overshoot, undershoot or double threshold crossing? Check CPOL, CPHA, CS setup and hold on logic analyzer Halve clock: ringing same, errors gone? Add series termination at source, reduce drive or slew Re-measure at receiver and re-run error count

Series versus parallel termination

Series, at driverParallel, at receiver
Value for 50 ohm trace22 to 33 ohm, close to MCU pinAbout 50 ohm to ground, at flash pin
Effect on first incident waveLaunched wave is halved, returning reflection absorbed at sourceFirst wave is full size, reflection absorbed at load
Power costLow, only during transitionWhen the line is high, current through the resistor is about VDD / 50 ohm = 66 mA at 3.3 V. The flash CMOS input is high impedance, so the resistor dominates that current. When the line is low, that path carries little current.
Best forSingle slave, point to point, most SPI flash layoutsMulti-drop or stubbed buses where the far end must be quiet immediately
Main riskToo large a value slows the edge so the receiver misses setupThe driver must source the termination current in addition to the capacitive load. With a weak driver or a series resistor also fitted, the high level can droop.

Parallel termination on a single-slave SPI bus usually buys nothing and costs current on every high clock level. I would only consider it if the scope showed the first incident wave already violating the flash input limits, for example overshoot past the absolute maximum rating, before any reflection could return.

Applying it in firmware and hardware

Hardware owns the resistor. Firmware owns drive strength and slew rate where the MCU exposes them, and it owns the test that proves the change. On an STM32F4 the GPIO speed setting is the slew control:

C
/* STM32F4, checked against CMSIS device headers */
GPIO_InitTypeDef spi_gpio = {0};
spi_gpio.Pin = GPIO_Pin_5 | GPIO_Pin_7;   /* SCLK, MOSI */
spi_gpio.Mode = GPIO_Mode_AF;
spi_gpio.OType = GPIO_OType_PP;
spi_gpio.PuPd = GPIO_PuPd_NOPULL;
spi_gpio.Speed = GPIO_Speed_25MHz;        /* slower slew than GPIO_Speed_100MHz */
GPIO_Init(GPIOB, &spi_gpio);

I would treat that as a temporary diagnostic knob, not the permanent fix. A permanent design should pass at a sane slew setting with the series resistor fitted, because relying on the slowest GPIO setting leaves no margin for process and temperature variation in rise time. The sequence I would run is: measure at the receiver, fit 27 ohm series on SCLK and MOSI, re-measure, then step the clock back up to the target rate and count errors over at least a million frames at minimum and maximum supply voltage. If ringing persists, I would look for a stub to a test point or a second slave, a ground via missing near the flash, or a trace routed over a plane split. Those discontinuities reflect energy no resistor value fully hides.

Two failure modes catch people out. First, measuring with a long probe ground and fixing a probe artifact with termination that makes the real signal worse. Second, slowing the slew so far that the edge crosses the receiver threshold slowly and jitter grows, which trades ringing errors for setup errors at the flash. The scope at the receiver pin, at the final clock rate, is the only evidence that settles both.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-53How would you implement secure boot on a Cortex-M device so it only runs a signed image, keep the signing keys safe, and lock the debug port in production?

The 90-second answer

I would put a small verifier in code the attacker cannot change, have it check a signature on the application before jumping to it, keep the private signing key off the device, and disable SWD in the production lifecycle. If any check fails, the device does not jump to the application. It stays in the ROM bootloader or boots a recovery image.

On many Cortex-M parts, such as STM32H7 and STM32U5, that verifier is the ROM bootloader or a first-stage bootloader in protected flash. It holds a hash of the vendor public key in OTP or eFuses. The application image carries a signature made with the matching private key. The ROM checks the signature, then transfers control.

valid invalid Reset ROM bootloader runs Check signature on application Jump to application Stay in ROM or boot recovery

What each part does

PartHow it worksWhat it stops
Signed imageBootloader verifies ECDSA P-256 or Ed25519 signature over the image hash before jumpingModified or unsigned firmware running at reset
Public key hash in OTPDevice stores SHA-256 hash of the public key in one-time programmable memoryReplacing the public key in flash to accept a different signing key
Private key offlineSigning happens on a build machine or HSM, never on the device or in the source repoExtracting the signing key from a dumped flash image
Debug lockedProduction lifecycle disables SWD and JTAG, and flash readout protection blocks debugger readsAttaching a debugger to read flash, patch RAM, or skip the signature check

Key storage

The device needs only public material. The OTP hash lets the bootloader confirm that a signature was made by the vendor key without storing the full key in writable flash. The private key stays offline. A release build is signed there, and the signed image is what gets flashed.

I would not store a device private key in application flash. If an attacker dumps flash, they get both the code and the key that code was meant to protect. Where a device needs its own identity, for example a certificate for a cloud connection, I would generate that key pair inside a secure element or in TrustZone secure firmware and export only the public part. The application can ask that block to sign, but it cannot read the key out.

The check itself

C
/* Cortex-M33, ECDSA P-256, application in internal flash */
int boot_application(const image_header_t *hdr, const uint8_t *image, size_t len)
{
    if (hdr->image_len != len) return -1;
    if (ecdsa_verify(pubkey_hash_from_otp, hdr->signature, image, len) != 0)
        return -1;
    jump_to_application(image);
    return 0;
}

The signature should cover the header as well as the code bytes, including the image length and load address. If it covers only the payload, an attacker can keep a valid payload and edit the header to point it at a different address.

Locking debug

Debug locking is a lifecycle setting, not a flag the application sets at runtime. In production, SWD and JTAG are disabled and the debugger cannot read internal flash. Re-enabling debug then requires a full chip erase, which wipes the application, or a signed debug token checked against the same vendor public key.

I would pick the erase option for most products. It is simple and there is no token to leak or replay. The cost is that a returned field unit loses its firmware and logs when a technician re-enables debug. Signed tokens avoid that cost, but the token needs a nonce and a short expiry, or a captured token becomes a permanent way back in. I would also block booting from external flash or an SD card in production, since that lets an attacker run unsigned code without changing internal flash.

What I would test

A corrupted image, a truncated image, and an image signed with the wrong key should all leave the device in recovery, not in a half-started application. I would also test that SWD attach fails on a production part and succeeds only after the erase step I chose. A secure boot that bricks the device on the first bad update is not finished, so the recovery path needs the same signature check as the main application.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-54What does an anti-rollback counter in signed firmware metadata prevent, and how does the bootloader enforce it?

The 90-second answer

An anti-rollback counter stops an old, validly signed firmware image from being installed again after a newer version has been committed. The bootloader reads the counter from the signed metadata in the candidate image and compares it with the counter already committed on the device. If the candidate counter is lower, the bootloader rejects it and boots the current image.

The signature alone cannot do this. A version 10 image signed by the vendor still verifies correctly after version 11 is running. The counter adds freshness. It turns "signed by the vendor at some point" into "signed by the vendor and at least as new as what this device has already accepted."

No Yes Candidate image in inactive slot Verify signature over metadata Read candidate counter from metadata Read committed counter from secure storage Candidate counter >= committed? Reject image, boot current version Boot candidate, commit counter after confirmation

Where the committed counter lives

The committed value must not be stored in ordinary application flash that the update path can rewrite. If an attacker can write a downgraded image, they can also write a lower counter next to it and the check passes. Typical storage is a monotonic eFuse counter, a secure element, or replay protected memory in managed flash. The exact part differs by MCU family, for example STM32H7 secure storage or NXP i.MX eFuse, but the rule is the same: the update code can advance the value, it cannot rewind it.

The counter is committed after the new image boots and confirms itself, not when the image is downloaded. A common pattern is a trial boot flag. The bootloader boots the candidate, the application sets a confirmed flag once its own checks pass, and only then does the bootloader advance the committed counter. If power fails during the trial, the device falls back to the previous image and the counter stays where it was.

C
// Bootloader check, simplified. metadata is already signature verified.
bool counter_allows(const metadata_t *md)
{
    uint32_t committed = secure_counter_read();
    return md->rollback_counter >= committed;
}

// Called only after the new image has booted and confirmed itself.
void counter_commit(const metadata_t *md)
{
    uint32_t committed = secure_counter_read();
    if (md->rollback_counter > committed) {
        secure_counter_advance_to(md->rollback_counter);
    }
}

Worked trace

Assume the device has committed counter 11 and is running version 11.

CandidateSignatureCounter in metadataCommittedBootloader action
Version 12 updateValid1211Boot version 12, commit 12 after confirmation
Replay of version 10Valid1011Reject, boot version 11
Replay of version 11Valid1111Allowed by counter, subject to other policy
Tampered version 12Invalid1211Reject on signature before counter matters
Version 12, power lost during trialValid1211Boot version 11 again, counter remains 11

The equal case matters. Using >= rather than > allows a reinstall or recovery of the same version. Using > would block a legitimate reflash of the current release.

Failure modes to name in an interview

A counter stored in a normal flash sector fails the whole scheme, because the attacker rewrites both image and counter. A counter advanced on download rather than on confirmed boot can brick recovery, since a failed image consumes the counter and the previous good image then looks like a downgrade. A counter that increments on every boot attempt has the same problem in slower form. The counter also needs to be inside the signed metadata. If it sits outside the signed bytes, an attacker can edit it upward or downward without breaking the signature. That is why the signature covers the counter, the image hash, the version, and the target model together.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-55How would you lock JTAG/SWD in production with fuses and lifecycle states while still preserving factory test and a field debug option?

The 90-second answer

I would not treat debug lock as a single fuse. I would use a lifecycle with at least four states: development, factory test, production, and return or field debug. Each transition is one way except for a controlled return path that requires physical access and, ideally, a mass erase. Factory test runs in the factory test state, before the production fuse is blown. Field debug in production is not open SWD. It is either disabled, or it requires an authenticated unlock that the bootloader checks before it re-enables the port for a limited session.

The key judgement is ordering. Once the production fuse is blown, you cannot recover a unit that failed test because the test fixture needed SWD to load code, read calibration, or check a peripheral. So the sequence is: program and provision in factory test, run electrical and functional test, verify the image and device identity, then blow the production fuse as the last step on the line. If test fails after that, the unit is scrap or goes through a return flow that erases flash and keys.

Development: open SWD Factory test: open SWD, test firmware Production: SWD locked Field debug: authenticated, time limited Return: physical access, erase, back to factory

Lifecycle and what each state allows

StateJTAG/SWDFlash readBoot sourceIntended user
DevelopmentOpenOpenAny, including serial/USB bootloaderEngineer on bench
Factory testOpen, fixture onlyOpen to fixtureInternal flash or test imageProduction line
ProductionLocked or authenticated onlyBlockedInternal flash onlyCustomer, field service
ReturnOpen after eraseBlocked until eraseInternal flashDepot with physical access

On STM32 parts this maps to Readout Protection levels. Level 1 blocks flash readout through the debug port but allows debug with a mass erase on reconnect. Level 2 is irreversible, disables JTAG/SWD, and forces boot from internal flash. On Nordic nRF52/nRF53 parts the equivalent is APPROTECT in UICR, which blocks SWD until a chip erase. The names differ, the pattern is the same: a reversible level for development and a final level you only blow after test passes.

Preserving factory test

Factory test needs more than SWD. The fixture usually needs to program flash, set a serial number, write calibration, inject a device key, and read back a hash. I would run that in factory test state with a test firmware or with the production firmware exposing a test command over UART or USB, not over open SWD on the finished unit. The production image should contain a factory test mode that is reachable only before the production fuse is blown, or that requires a fixture signal on a GPIO that is not populated on the customer board.

A common failure is blowing the fuse in the same script that programs the image, then discovering the test needs to read back flash to verify programming. The fix is to split the script. Program, provision, test, verify, then lock. The lock step should check a flag written by the test firmware, such as a test pass record in flash, before it blows the fuse. If that flag is missing, the script aborts and the unit is diverted.

Field debug without open SWD

For field debug I would offer three options in order of preference. First, no debug port at all, with diagnostics over the normal interface, such as a UART log or a BLE diagnostic service. Second, authenticated debug: the bootloader accepts a signed unlock token over UART or USB, checks its expiry and device binding, enables SWD for one boot, and logs the event. Third, SWO trace only, which gives printf and PC sampling without full halt and memory access. Open SWD in the field is the last resort, because anyone with a $10 probe can read firmware and keys if the part allows it.

The unlock token needs to be bound to the device. A token that works on every unit is a leaked token that works on every unit. I would derive the expected response from a device unique key that never leaves the secure element or the protected flash region, and I would include a nonce from the device so a captured token cannot be replayed.

C
/* Checked against STM32H7 and nRF53 style lifecycle APIs, pseudocode for structure */
typedef enum { LC_DEVELOPMENT, LC_FACTORY, LC_PRODUCTION, LC_RETURN } lifecycle_t;

int lifecycle_enter_production(void)
{
    lifecycle_t state = lifecycle_read();
    if (state != LC_FACTORY) return -1;          /* never skip factory test */
    if (!factory_test_pass_record_valid()) return -1;
    if (!provisioning_complete()) return -1;     /* serial, calibration, key */
    lifecycle_request_transition(LC_PRODUCTION); /* blows fuse, may reset */
    return 0;
}

Failure modes I would name in the interview

Blowing the irreversible level before the bootloader is proven bricks the return path. If the bootloader has a bug and the production image fails to boot, a Level 2 style lock with no serial bootloader means the board cannot be recovered. I would test the return flow on a sample of locked units before release, including the erase time and the effect on calibration data.

A second failure is locking SWD but leaving the ROM bootloader open. Many parts boot from USB, UART, or SD if a pin is strapped. If that bootloader can read flash or load unsigned code, the fuse did not lock anything. Production state must disable alternate boot sources or require authentication there too.

A third failure is assuming the fuse state survives a firmware update. It does, fuses are one time programmable, but a buggy update that enables debug in software defeats it. The production firmware should read the lifecycle state at boot and refuse to enable SWD, and the bootloader should enforce the same check before jumping to the application. That way a compromised application cannot reopen the port on its own.

I would close by stating the trade-off plainly. Every field debug option you keep is an attack surface you keep. The design goal is not zero debug, it is debug that requires physical access, authentication, and an audit trail, with factory test completed before the point of no return.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-56How would you use a hardware AES accelerator on a Cortex-M MCU for 1 KB messages, covering key storage, DMA setup, latency, and side-channel risks?

The 90-second answer

I would load the key once into the accelerator key registers at boot, then use DMA to move data between RAM and the CRYP peripheral while the CPU does other work. Polling block by block wastes the point of the hardware. The accelerator also does not make the design side-channel proof. It removes the obvious software timing leak, it does not stop power or electromagnetic leakage, and it does not fix a reused nonce.

Assume a STM32F4-class part at 84 MHz, AES-128, 1 KB messages, ECB or CBC for the latency comparison. GCM or CCM changes the arithmetic because of the extra GHASH or counter work, and the mode choice matters more than the raw block speed.

Key storage

The key should never sit as plaintext in internal flash or in a RAM buffer that survives the operation. On parts with OTP or a secure key store, I derive or unwrap the working key at boot, write it directly to the CRYP key registers, then clear the source buffer. On a part without that, I load from a protected region with readout protection enabled, debug disabled in production, and I zeroize the key registers and any key schedule registers on tamper, reset, or when the session ends. Debug access is the practical failure mode here. If SWD can read RAM after boot, the key registers are only a speed bump, so production fusing and readout protection level decide the real protection.

C
/* STM32F4 HAL, checked against STM32F4 HAL CRYP driver */
static CRYP_HandleTypeDef hcryp;

void aes_init(void)
{
    hcryp.Instance = CRYP;
    hcryp.Init.DataType = CRYP_DATATYPE_8BIT;
    hcryp.Init.KeySize = CRYP_KEYSIZE_128BIT;
    hcryp.Init.Algorithm = CRYP_AES_ECB; /* use CBC/GCM for real traffic */
    HAL_CRYP_Init(&hcryp);

    /* Load from OTP-derived buffer, then clear that buffer. */
    load_key_to_cryp_registers(key_buf);
    secure_zero(key_buf, sizeof(key_buf));
}

HAL_StatusTypeDef aes_encrypt_dma(const uint8_t *in, uint32_t len,
                                  uint8_t *out, uint32_t *out_len)
{
    return HAL_CRYP_EncryptDMA(&hcryp, (uint8_t *)in, len, out, out_len);
}

secure_zero needs a volatile pointer or a compiler barrier. A plain memset on a local buffer can be optimized away at -O2 if the buffer is never read again.

DMA and latency

DMA pays off when the transfer is long enough to hide setup cost. The figures below are a labelled hypothetical worked example, not a claim about the STM32F407 CRYP throughput. Check the datasheet and measure on your part before quoting a number in a design review. Assume software AES at 1,800 cycles per 16-byte block and hardware at 40 cycles per block. For 1 KB there are 64 blocks.

Software: 64 x 1,800 / 84 MHz = 1.37 ms, with the core blocked throughout.

Hardware: 64 x 40 / 84 MHz = 30.5 us, plus about 2 us of DMA setup in this example, for about 32.5 us total. Polling has roughly the same hardware time, but the CPU spins on status flags for that whole period instead of doing other work.

MethodCPU cost for 1 KBLatency in this exampleMain risk
Software AESBlocks the core for the whole operation1.37 msTiming and cache leaks, missed deadlines
CRYP pollingCPU spins on status flagsAbout 30.5 us of hardware timeWasted cycles, priority inversion in a loop
CRYP + DMA + IRQSetup only, DMA moves dataAbout 32.5 us including setupCache and buffer lifetime bugs

On a cached Cortex-M7 the DMA buffers need cache maintenance. Clean the transmit buffer before DMA reads it, invalidate the receive buffer before the CPU reads it, align both to the cache line size, and keep them out of a stack frame that can be reused. The completion interrupt must also check the CRYP error flags. A DMA transfer that finishes with a peripheral error flag set is not a successful encryption.

Task queues 1 KB buffer Clean cache, start CRYP DMA DMA moves data to CRYP CRYP encrypts block by block DMA writes output buffer IRQ: invalidate cache, check flags Task consumes output

Side channels and misuse

Hardware AES still leaks through power draw and EM. The leakage per block is smaller and less data-dependent than a table-driven software implementation, but a lab attacker with a near-field probe can still correlate traces. If the threat model includes that attacker, the answer is a certified secure element or an accelerator with masking, not a claim that hardware equals immunity. I would also avoid an encryption oracle. Rate limit attempts, authenticate before decrypting, and use AES-GCM or AES-CCM with a unique nonce per message. Nonce reuse in GCM is catastrophic, it leaks the authentication key stream, and no accelerator prevents it.

Two failure modes I check in review: the key left in a DMA-accessible RAM buffer after the transfer, and the output buffer read before the completion interrupt because a timeout fired and the task moved on. Both are easy to miss in a driver that works on the bench and fails under load.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-57Your device receives a 256 KiB OTA image in 4 KiB chunks over UART and can lose power at any point: how do you verify each chunk, resume where you left off, and decide when the image is safe to install?

The 90-second answer

Write each chunk to the inactive flash slot, check it before you record it, and keep a bitmap of which chunks passed. On reboot, read that bitmap, recheck the last chunk, and ask the host to resend from the first missing one. Do not mark the image installable until the bitmap is full and a check over the whole image matches the value in the update header.

Assume two equal slots, one running the current firmware and one staging the new image, and a small metadata area that survives power loss. Chunk size is 4 KiB, so a 256 KiB image has 64 chunks. The host sends each chunk with its index, the total chunk count, the payload, and a CRC-32 of the payload.

Verifying and recording a chunk

Program the payload at staging_base + index * 4096, read it back from flash, and compute CRC-32 over the read-back data. Only if it matches the CRC sent by the host do you set that chunk's bit in the bitmap and store the CRC in metadata. Read-back matters because a flash program can report success while the data did not land, and the CRC catches a torn write after power loss.

C
bool accept_chunk(uint32_t index, const uint8_t *payload, uint32_t sent_crc) {
    uint8_t *dst = (uint8_t *)(STAGING_BASE + index * CHUNK_SIZE);
    flash_program(dst, payload, CHUNK_SIZE);
    if (crc32(dst, CHUNK_SIZE) != sent_crc) {
        return false;  /* bitmap bit stays clear, host will resend */
    }
    meta.chunk_crc[index] = sent_crc;
    meta.bitmap |= (1ULL << index);
    meta_save();
    return true;
}

Metadata itself needs protection against a torn write. Keep two copies and save the new bitmap to the older copy, then check its own CRC before treating it as valid. On boot, use the copy with a valid CRC and the higher sequence number. If the newest copy is torn, the previous bitmap is still there and you simply resend a few chunks.

Resume after power loss

On reboot the updater loads the valid metadata, then scans the bitmap from chunk 0. The first clear bit is the resume point. Before resuming, recheck the chunk just before that point, because power may have failed after programming it but before meta_save() finished. If its read-back CRC no longer matches, clear its bit and resume one chunk earlier.

EventBitmapAction
Chunks 0 to 16 acceptedbits 0-16 setcontinue
Power lost during chunk 17bits 0-16 setreboot, resume at 17
Chunk 17 sent, CRC mismatch on read-backbit 17 clearhost resends 17
Chunks 17 to 63 acceptedall 64 bits setrun whole-image check
Whole-image CRC matches headerinstall flag setbootloader may boot new slot

A duplicate chunk, sent because the host timed out waiting for an acknowledgement, is harmless. Its CRC already matches the stored value, so you acknowledge it without rewriting the bitmap.

When to commit

A full bitmap proves every chunk arrived intact at some point. It does not prove the chunks belong to the same image, so the header also carries the image length and a CRC-32 or SHA-256 over the complete image. After the last chunk, compute that check over the staging slot. Only on a match do you set the install flag that tells the bootloader to try the new slot. On mismatch, clear the bitmap, erase the staging slot, and keep booting the old firmware.

fail pass no yes fail pass Receive chunk Program staging slot Read back and check CRC-32 Set bitmap bit and save metadata All chunks set? Check whole-image CRC Clear bitmap, keep old slot Set install flag

The ordering is the safety property. No chunk is trusted until read-back passes, no resume point is trusted until the bitmap and the previous chunk are rechecked, and no image is installed until both the bitmap and the whole-image check pass.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-58What metadata should a firmware image carry so the bootloader can check hardware compatibility before booting it?

The 90-second answer

Put a fixed header at the start of the image, outside the code the CPU executes. The bootloader reads it before it jumps, checks it against the board it is running on, and only then trusts the payload. If any check fails, it does not boot that slot. It tries the other slot or a recovery image.

The header needs to answer four questions without running the application: is this image for this hardware, was it built for this bootloader, is it complete and untampered, and should it be booted at all or treated as a trial or recovery image.

C
/* Checked against Cortex-M4, GCC 13, packed so layout is stable across toolchains */
typedef struct __attribute__((packed)) {
    uint32_t magic;            /* 0x46494D47 "FWIM" */
    uint16_t header_len;       /* bytes in this header, for forward compatibility */
    uint16_t hw_id;            /* board revision this image was built for */
    uint32_t min_bootloader;   /* lowest bootloader version that understands this image */
    uint32_t image_len;        /* payload length in bytes, excluding header */
    uint32_t crc32;            /* CRC-32 of payload, or signature offset if signed */
    uint32_t anti_rollback;    /* monotonic version, never decreases */
    uint32_t flags;            /* bit 0: recovery image, bit 1: trial boot */
} fw_header_t;

hw_id is the core of hardware compatibility. The bootloader gets its own ID from a board strap, a resistor divider read by an ADC, or a one-time-programmable register burned at manufacturing. It compares the two. A mismatch means the image was flashed to the wrong board, for example a 24 V variant image on a 12 V board, and booting it could drive the wrong pins or clocks.

min_bootloader stops an old bootloader from booting a new image that uses a feature it does not know, such as a new vector table relocation or a larger header. image_len stops a truncated image, common after a power loss during flashing, from being treated as valid. crc32 or a signature over the payload catches corruption in flash. anti_rollback is compared with a counter in OTP or in a wear-levelled flash page that the bootloader only increments.

FieldBootloader checkOn failure
magicequals 0x46494D47skip slot, try other slot
hw_idequals board ID from OTP or strapsskip slot, log HW_MISMATCH
min_bootloader<= running bootloader versionskip slot
image_lenfits in slot and matches flashed lengthskip slot
crc32 / signaturerecomputed over payload matchesskip slot
anti_rollback>= stored minimumskip slot, refuse downgrade
flagsrecovery or trial bit setboot only if primary slot invalid or trial count exceeded

Worked trace

Board ID is 0x0012. Slot A holds version 41, slot B holds version 42 marked trial.

StepSlot checkedResultAction
1A, hw_id=0x0012, CRC ok, version 41passcandidate
2B, hw_id=0x0012, CRC ok, version 42, trialpasscandidate, preferred
3Boot B, application never sets confirmed flagtrial counter increments in flashnext reset
4B again, trial counter reaches 3rejectedboot A, mark B invalid

That trial and confirmed mechanism is the recovery behaviour. A new image boots in trial mode. The application, once it has passed its own self tests, sets a confirmed flag in a separate flash page. If it crashes or loses power before confirming, the bootloader counts the attempts and falls back. The recovery image is a third, minimal image with flags bit 0 set. It does not run the application. It exposes a UART or USB loader so a technician can reflash a board whose both application slots are invalid.

No Yes No Yes No Yes Yes No Read header Magic, hw_id, length ok? Try other slot CRC or signature ok? Version >= anti-rollback minimum? Confirmed or trial allowed? Jump to image Boot recovery image

Two details candidates get asked about. First, keep the header format versioned with header_len, so a future bootloader can skip fields it does not know instead of misreading the payload offset. Second, never put the CRC or signature inside the payload it covers. The bootloader computes it over a defined range, header fields it trusts plus payload, and the build script writes the result back into the header after the payload is final. If the header itself is corrupted, the magic and length checks fail first and the slot is skipped, which is the safe outcome.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-59How would you design factory programming and provisioning so each unit gets a unique serial number, calibration data and device key, and a leaked factory image cannot clone them?

The 90-second answer

I would never put a master key, a batch key, or a plaintext device key on the factory PC, the test jig, or in a firmware image. A provisioning server backed by an HSM derives a unique key per serial number, encrypts a small provisioning record to that device, and the jig only relays opaque bytes. The device writes the record to a dedicated flash partition, verifies it, burns the serial number into one-time programmable storage, then disables programming and debug access. If the factory image leaks, it contains no secret that can clone a unit.

Assumptions I state up front: the MCU has a hardware unique ID or a secure element, a bootloader that can verify a signature, and at least two flash slots or a journal for the provisioning partition. Without OTP or a secure element, cloning resistance is limited and I say so.

Flow

Provisioning server + HSM Allocate serial, derive device key Build signed, encrypted record Jig relays over authenticated channel Device verifies, writes to inactive slot Verify readback, commit, burn OTP, lock debug

The server allocates serials from a database with a unique constraint. Allocation is idempotent: a retry with the same job ID returns the same serial instead of burning a second one. The HSM derives the device key with HKDF-SHA256 using the serial number and device UID as context, so the same master key produces unrelated keys per unit. Calibration data, measured on the line, is bound into the same record and signed by the server key. The device checks the signature and a monotonic sequence number before accepting it, which stops a replay of an older calibration record.

StepWho holds the secretFailure if done wrong
Derive keyHSM onlyBatch key on PC clones every unit
Transport recordEncrypted, authenticatedJig logs plaintext keys
Write recordDevice, dual slotPower loss leaves a half written key
CommitDevice after readback CRCCorrupt calibration boots silently
LockOTP, debug disabledField reprogramming extracts key

Device side write

The record lives in two slots. The device writes the inactive slot, reads it back, checks CRC and signature, then flips a commit flag. A power cut before the flip leaves the old slot valid.

C
// Checked against C11, Cortex-M4, 256-byte provisioning slots.
typedef struct {
    uint32_t seq;
    uint32_t serial;
    uint8_t  device_key[32];
    int16_t  cal_offset_q15;
    uint32_t crc32; /* over all preceding bytes */
} prov_record_t;

int prov_commit(const prov_record_t *rec, int slot)
{
    if (flash_write(slot, rec, sizeof(*rec)) != 0) return -1;
    prov_record_t back;
    flash_read(slot, &back, sizeof(back));
    if (crc32(&back, sizeof(back) - 4) != back.crc32) return -1;
    if (!verify_signature(&back)) return -1;
    return slot_flip(slot); /* single word write, atomic on this flash */
}

After commit, the device burns the serial into OTP, sets the debug-disable and flash-read-protect bits, and zeroises the RAM buffer that held the key. The jig never sees the key in plaintext, and the provisioning application on the PC holds only ciphertext plus a job ID.

Leak and failure modes

Three leaks I design against. First, logs: the server and jig log serial, job ID, pass or fail, and a key fingerprint (first 8 bytes of SHA-256 of the key), never the key or the full record. Second, the test fixture: it runs signed code, its firmware is checked at boot, and its UART or SWD logs are disabled in production mode. Third, operator access: the HSM requires dual control for master key export, which I disable entirely, and every derivation is audited with operator, station and time.

Power loss during OTP burn is the awkward case. OTP writes cannot be undone, so I burn the serial only after the record verifies, and I make the burn itself a single fused word where the hardware allows it. If a unit fails after burning, it is scrapped or reworked under a new job that references the burned serial, rather than reusing it.

Scale check, with hypothetical figures: at 5,000 units per day and a 256-byte record, the line writes about 1.3 MB of provisioning data per day, trivial for flash, but the server must handle 5,000 HSM derivations per day plus retries. That is under 0.1 derivations per second on average, so a single HSM is ample, and the bottleneck becomes jig cycle time, not crypto.

The trade-off I accept: per-device derivation and dual-slot writes add about 200 ms per unit and require a bootloader that understands the record format. The alternative, one shared key written by a PC tool, is faster to build and fails catastrophically the first time a laptop is lost.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-60Your board has JTAG boundary scan on the MCU but no test points for a QFN sensor, and you must ship 500 units a day: how do you split coverage between boundary scan and ICT, and where do programming verification and screening fit?

The 90-second answer

I would let boundary scan and ICT share the solder fault coverage, then program and verify, then screen. Boundary scan covers digital interconnect through the MCU and other scan capable parts. ICT covers passives, analogue parts and the QFN sensor that has no scan chain and no test points. Programming verification proves the signed image and the per unit serial and key landed correctly. Screening catches marginal units that pass at room temperature.

Assume a Cortex-M board, JTAG available, bed of nails fixture, 500 units per day in one 7.5 hour shift. That gives 54 seconds per board for test plus handling. I would run scan and ICT first so a solder fault never consumes programming time.

Boundary scan and ICT Program over SWD Read back and verify hash Functional check Burn-in screen

Boundary scan against ICT

Boundary scan shifts patterns through boundary cells in the MCU, CPLD and similar parts. It checks opens and shorts between scan pins, stuck at faults and pull resistors. It needs a working JTAG chain and a BSDL file that matches the fitted silicon revision. It cannot measure a resistor value or test a part with no scan chain.

ICT drives test points with a bed of nails. It measures passives in circuit, checks analogue thresholds and can find a reversed diode or a missing capacitor. It needs a test point on each node it must reach. The QFN sensor in this design has neither a scan chain nor test points, so neither stage reaches its internal logic. That gap has to be closed by functional test, where firmware reads the sensor over I2C or SPI and checks its ID register and a known stimulus.

FaultBoundary scanICTFunctional test
Open between two MCU pinsYesYes, if test points existSometimes
Wrong resistor valueNoYesNo
Missing capacitor on power railNoYesIndirectly, through ripple or reset
QFN sensor solder openNoNo, no test pointYes, ID read fails
Wrong firmware imageNoNoYes, version check

The trade-off is coverage against fixture cost. Boundary scan needs fewer fixture pins and reaches pins under BGAs. ICT needs a pin per node and a test program per board revision, but it measures analogue values that scan cannot. I would target scan for digital interconnect and ICT for passives and analogue, and accept that the sensor is covered only functionally.

Programming verification

Programming over SWD is not done until readback matches. The station computes a SHA-256 hash of the readback and compares it with the hash in the signed manifest. It also writes the unique serial number, calibration constants and device key, and logs serial, image version and hash against the board barcode.

Python
# Host side, Python 3.11
import hashlib

def verify(image: bytes, readback: bytes, expected: str) -> bool:
    return len(image) == len(readback) and hashlib.sha256(readback).hexdigest() == expected

A failed verify gets one retry after reset. A second failure rejects the board. Repeated failures on one station point to SWD signal integrity or a weak flash supply, so the station logs retries as a separate yield metric.

Screening and throughput

Screening removes weak units that pass at 25 C. For industrial hardware I would burn in at elevated temperature and voltage for a set period, then repeat functional test. A typical screen is 85 C operating for 4 to 24 hours at the top of the normal supply range, staying inside absolute maximum ratings. Temperature cycling from -40 C to 85 C stresses solder joints, and I would run that on a sample per lot unless field failure cost justifies 100 percent.

Hypothetical timing for the 500 per day line: scan plus ICT 20 seconds, programming and verify 15 seconds, functional test 10 seconds. That leaves 9 seconds for handling and retest inside the 54 second budget. At 98 percent first pass yield, 10 boards per day need rework. At 5 minutes per rework that is 50 minutes of technician time, so yield by stage has to be tracked or the line stalls.

Two checks keep the test honest. A known good golden board runs at shift start. A known bad board with a seeded open runs weekly to prove the test still fails. If the golden board passes and the bad board also passes, a fixture nail or a BSDL mismatch is the likely cause, not perfect production.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-61Your 1 kHz control loop on a 480 MHz Cortex-M7 misses its budget when the sensor filter runs from flash: how would you profile it with cycle counters and cache placement, and prove the improvement?

The 90-second answer

I would time the loop on the target, with interrupts running, and split the total into the filter, the PID math, and time lost to preemption. On a Cortex-M7 at 480 MHz, DWT CYCCNT counts one per core cycle, so a 1 kHz loop has 480,000 cycles per period and a 20 µs budget is 9,600 cycles. If the filter takes 4,200 cycles from flash with a cold instruction cache, moving it to ITCM and its tables to DTCM usually removes most of that. I would show the same measurement before and after, on the same build flags and the same replayed sensor data.

C
// Cortex-M7, CMSIS-Core 5.x. Enable CYCCNT once at startup.
#include "core_cm7.h"

static inline void cycles_init(void)
{
    CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
    DWT->CYCCNT = 0u;
    DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}

static inline uint32_t now_cycles(void)
{
    return DWT->CYCCNT;
}

uint32_t t0 = now_cycles();
filter_step(&s);
uint32_t dt = now_cycles() - t0; /* unsigned subtraction handles one wrap */

CYCCNT is 32 bits, so at 480 MHz it wraps every 8.9 seconds. Unsigned subtraction is correct for a window shorter than that, which a control loop is. I log results to a RAM ring buffer, not printf inside the loop, because a UART print at 115200 baud costs milliseconds and changes the timing under test.

For a repeatable number I run the loop free-running for 10,000 iterations, record min, median and p99, and toggle a GPIO at entry and exit for a logic analyzer check. The GPIO trace catches a case the counter hides: a higher priority ISR preempting the loop and inflating p99 while the median looks fine.

BuildMedian cyclesp99 cyclesTime at 480 MHz (p99)Misses in 10,000
Baseline, code and tables in flash4,1806,90014.4 µs312
Filter in ITCM, tables in DTCM1,2401,6103.4 µs0
Same as above, -O2 to -O3 only1,1901,5803.3 µs0

Those figures are a labelled worked example on that clock. The method is the point: same input sequence, same interrupt load, only placement changed. Changing compiler flags at the same time makes the gain unattributable.

ITCM and DTCM on the M7 are tightly coupled memories with no cache latency. I place the filter and PID step, which run every cycle, in ITCM, and the coefficient table and state struct in DTCM. DMA buffers stay in SRAM, aligned to 32 bytes, the M7 cache line size, and I clean before DMA transmit and invalidate after DMA receive. Whether a DMA engine can reach DTCM depends on the specific part and its bus fabric, so I check the device reference manual for the DMA master I am using and keep DMA buffers in a region that manual lists as accessible. On parts where DTCM is not reachable by that DMA, a buffer placed there simply never transfers.

LD
/* Linker fragment: hot code and data */
.itcm_text : AT(FLASH_ITCM_LOAD) {
    *(.itcm_text.filter*)
    *(.itcm_text.pid*)
} > ITCM

dtcm_data (NOLOAD) : {
    *(.dtcm.filter_state*)
    *(.dtcm.filter_coeff*)
} > DTCM
C
__attribute__((section(".itcm_text.filter"), noinline))
static float filter_step(filter_state_t *s)
{
    /* ... */
    return 0.0f;
}

__attribute__((section(".dtcm.filter_coeff"), aligned(32)))
static const float kCoeff[64] = { /* ... */ };

noinline on the definition matters. Without it the compiler may inline the filter into a caller in flash and undo the placement, or clone it and waste ITCM. I check the map file and disassembly after linking to confirm the symbol landed in ITCM, because a section name mismatch silently falls back to flash.

no yes Baseline: time loop with CYCCNT, log to RAM Split time: filter vs PID vs ISR preemption Move hot code to ITCM, tables and state to DTCM Re-run same 10,000-iteration trace p99 within budget and no misses? Check map file, GPIO trace, DMA buffers in accessible SRAM

Failure modes I check before claiming a win: cold cache on the first iteration after a DMA burst that evicted the loop, which shows up as a high max but a normal median; a table crossing a 32-byte cache line boundary and causing two misses per access; and false sharing if DMA writes the same cache line as the filter state. I also re-measure with the debugger detached, since SWD halt and ITM trace can stall the core on some parts.

If p99 still misses, the next step is reducing work: a fixed-point filter, a shorter table, or running the filter at 500 Hz instead of 1 kHz if the control analysis allows it. Placement buys a factor of two to three on this class of loop. It does not fix an algorithm that needs ten times the budget.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-62On Cortex-M7, to what boundary must a DMA buffer's start address be aligned for cache maintenance to work correctly?

The 90-second answer

Align the buffer start to a full cache line, 32 bytes on most Cortex-M7 parts. Cache maintenance works on whole lines, so an unaligned start leaves the first partial line unmaintained.

C
/* Checked against CMSIS on STM32H7, Cortex-M7, 32-byte line */
#define CACHE_LINE_BYTES 32u

__attribute__((aligned(32)))
static uint8_t dma_tx[256];

void dma_tx_start(void)
{
    SCB_CleanDCache_by_Addr(dma_tx, sizeof(dma_tx));
    __DSB();
    dma_start(dma_tx, sizeof(dma_tx));
}

SCB_CleanDCache_by_Addr rounds the address down and the end up to line boundaries internally in CMSIS, but that rounding is exactly the hazard. If the buffer starts mid-line, the bytes before it in that line belong to another variable. Cleaning or invalidating that line then affects that variable too. Aligning the buffer and padding its size to a multiple of 32 bytes keeps the maintained lines belonging only to the buffer.

Buffer startLine start usedResult
0x200001000x20000100Aligned, only buffer lines maintained
0x2000010D0x20000100First line shared with preceding data
0x200001200x20000120Aligned, only buffer lines maintained

Worked example, hypothetical addresses: a 100-byte buffer at 0x2000010D spans lines from 0x20000100 to 0x20000180, so 128 bytes are maintained and the first 13 bytes of the first line are not part of the buffer. Moving the buffer to 0x20000100 removes that sharing.

Do not hard-code 32 bytes blindly for every M7. Read the line size from the Cache Type Register, SCB->CTR, at startup if the same firmware runs on different M7 variants. On the common STM32H7 and i.MX RT1060 parts it is 32 bytes, and the aligned(32) attribute matches it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-63How does TrustZone-M on a Cortex-M33 split secure and non-secure firmware, and what does calling a secure AES function from non-secure code cost versus a normal function call?

The 90-second answer

TrustZone-M on a Cortex-M33 divides the address map into a secure world and a non-secure world. Secure firmware holds boot policy, keys and the crypto accelerator. Non-secure firmware runs the application and most drivers. Hardware checks the world on every access. A non-secure call into secure code cannot jump directly to a secure function. It must go through a small NSC veneer, and that detour is the cost to measure.

Partitioning uses two attribution units. The IDAU gives the fixed map for the chip, such as boot ROM and one-time programmable storage. The SAU is programmable. Firmware writes SAU region registers with a base, a limit and attributes, then enables the SAU. A region marked secure faults when non-secure code reads, writes or executes it. A region marked non-secure is open to both worlds, which is how shared buffers work. Peripherals have the same attribution. A UART assigned secure will fault if non-secure code touches its registers.

ResourceSecureNon-secureShared
FlashBootloader, secure serviceApplicationNSC veneer page only
RAMSecure stacks, key materialApplication stacks and heapOne mailbox buffer
PeripheralsCrypto acceleratorUART, SPI, sensorsDoorbell interrupt

The veneer is the only legal entry. Non-secure code does a BL to an address in an NSC region. Hardware switches to secure state and the first instruction there is SG, secure gateway. That instruction branches to the real secure function. The secure function returns with BXNS. The hardware stacks and restores registers, switches to the secure stack pointer and clears secure-only registers on the way back. The linker places the veneer in the NSC section and marks the secure function so the compiler will not emit a direct cross-world call.

C
// Cortex-M33, Armv8-M. SAU region 0: secure flash, region 1: secure RAM,
// region 2: non-secure shared mailbox. NSC veneer placed by linker script.

__STATIC_FORCEINLINE void sau_setup(void)
{
    SAU->RNR = 0; SAU->RBAR = 0x10000000; SAU->RLAR = 0x1001FFFF;
    SAU->RNR = 1; SAU->RBAR = 0x20000000; SAU->RLAR = 0x2000FFFF;
    SAU->RNR = 2; SAU->RBAR = 0x20010000; SAU->RLAR = 0x20010FFF;
    SAU->CTRL = SAU_CTRL_ENABLE_Msk;
    __DSB();
    __ISB();
}

__attribute__((section(".nsc_veneer"), used))
void aes_encrypt_veneer(const uint8_t *in, uint8_t *out, size_t len)
{
    __asm__ volatile("sg");
    secure_aes_encrypt(in, out, len);
}

Cost comparison, with hypothetical figures for a 100 MHz M33. A normal non-secure function call and return takes about 20 cycles. A veneer call adds SG, BXNS, extra stacking and the stack switch, and takes about 60 cycles in this example. That is roughly 0.4 microseconds extra. The veneer itself is cheap. The expensive pattern is using the veneer as a general IPC channel for tiny transfers, where each call also wakes secure code, copies data through a mailbox and waits for a completion flag. That round trip can reach several microseconds, dominated by interrupt latency rather than SG.

Batching fixes it. Encrypting 256 bytes in one veneer call costs about 60 cycles of crossing overhead plus the hardware AES time. Encrypting the same 256 bytes as 256 one-byte calls costs 256 crossings, about 15,360 cycles of overhead alone, before any AES work. At a 1 kHz loop rate, one batched call per cycle is negligible. One-byte calls every cycle would consume about 15 percent of the period in crossing overhead in this example and add jitter.

Two failure modes show up in bring-up. A peripheral left in the wrong attribution faults on first use from the other world, so check the SAU and peripheral attribution before debugging the driver. A shared mailbox with no ownership flag races when non-secure code overwrites a request secure code is still reading. Use a state field in the mailbox, idle to pending to done, and have secure code reject a new request while state is pending. Write the state with a memory barrier so the other world sees the data before the flag.

Use the veneer for privileged operations such as signing, decrypting or releasing a key. Keep high-rate data paths in one world and cross only for the operation that needs protection.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-64Which of polling, interrupts or DMA gives the lowest latency to read a sensor's data-ready flag, and what does that choice cost in power and CPU load?

The 90-second answer

Polling gives the lowest latency. The CPU reads the data-ready flag in a loop and reads the data as soon as the flag sets, with no interrupt entry, no stacking and no wake-up delay. The cost is that the CPU stays awake and busy for the whole wait, so power and CPU load are the highest of the three methods.

Interrupts and DMA both let the CPU sleep or do other work while waiting. They add latency, typically a fraction of a microsecond to a few microseconds on a Cortex-M, in exchange for that saving.

MethodLatency to dataCPU while waitingPower while waitingTypical use
PollingLowest, one register read100%, spinningRun current, for example 12 mA at 84 MHzWait of a few microseconds in a control loop
InterruptEntry plus handler, about 0.5 to 2 usZero, can sleepSleep current, for example 2 uA in stopSporadic data-ready, low sample rate
DMASetup first, then hardware pacedZero after setupCore can sleep during transferBulk transfer, hundreds of bytes or more

Worked figures

Suppose a sensor sets data-ready 20 us after you start a read, and you read it at 1 kHz. Polling spins for 20 us per sample. That is 20 ms of spinning per second, 2% of the core, and the core never sleeps in that window. An interrupt would wake the core, run a 1 us handler, and return to sleep. Latency rises by roughly the interrupt entry time, but average current falls from run current to near sleep current between samples.

If the wait grows to 10 ms, polling burns 10 ms of run time per sample. At 1 kHz that is impossible, the loop cannot keep up. The same wait with an interrupt costs one entry per sample. That is why the rule is based on wait length, not just latency. Poll when the wait is shorter than the work you would save by sleeping.

Code shape

Polling a memory-mapped flag:

C
// C, Cortex-M, checked against STM32-style register map
while ((SENSOR->STATUS & SENSOR_RDY) == 0) {
    // No sleep here. This is the cost of the low latency.
}
uint16_t sample = SENSOR->DATA;

The same flag with an interrupt:

C
// C, Cortex-M
void EXTI0_IRQHandler(void) {
    uint16_t sample = SENSOR->DATA; // reading DATA clears RDY in hardware
    ring_push(&samples, sample);    // keep the handler short
}

DMA does not poll a flag at all for bulk data. You program the source, destination and length once, enable the channel, and the hardware moves bytes while the core sleeps. The core wakes on transfer complete or half transfer.

C
// C, pseudo setup for SPI or ADC DMA
DMA1_Channel1->CPAR = (uint32_t)&SPI1->DR;
DMA1_Channel1->CMAR = (uint32_t)rx_buffer;
DMA1_Channel1->CNDTR = RX_LEN;
DMA1_Channel1->CCR = DMA_CCR_MINC | DMA_CCR_TCIE | DMA_CCR_EN;

When polling is the wrong choice

Polling fails when the wait is long or unpredictable. A loop waiting for a sensor that can take 5 ms will block the rest of the firmware, delay the watchdog feed and miss deadlines in other tasks. It also fails on battery power, because spinning at run current for a 1% duty cycle sensor wastes most of the battery budget.

Interrupts fail in the opposite direction, when events arrive too fast. A per-byte interrupt at high baud rate or a noisy ready pin can flood the core. DMA fails when the buffer is in memory the DMA cannot reach, or on cached Cortex-M7 parts when the buffer is not cache maintained before and after the transfer.

So for lowest latency alone, polling wins. For a sensor driver that must also save power and CPU, you pick polling only when the wait is a few microseconds and the core has nothing else to do in that window.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-65A mechanical button bounces for up to 8 ms and a 12-bit ADC sensor is noisy at 1 kHz: how do you debounce and filter both without adding latency your control loop cannot tolerate?

The 90-second answer

Separate the two problems. A button is a discrete event with a bounded bounce interval, so you debounce by time: ignore edges until the level has been stable for longer than the worst bounce. A sensor is a continuous value with noise on every sample, so you filter by averaging, and you pay for that averaging in group delay. Picking one technique for both either leaves the button chattering or buries the sensor under lag.

Assume a 1 kHz control loop, a button that bounces for at most 8 ms, and a latency budget of 20 ms from press to the loop acting on it. A 10 ms stable-time debounce fits. For the ADC, assume white noise of about 4 LSB RMS on a 12-bit converter and a signal that moves slowly compared with 1 kHz. A first-order IIR with alpha = 0.2 cuts noise by roughly a factor of three and adds about 4 ms of group delay, which the loop can tolerate. If the signal can step quickly, that same filter is the wrong choice and you need a median filter or a shorter window.

Button: timestamp debounce, not a delay loop

Do not put delay(10) in an ISR or in the loop. Record the tick when the level changes and only accept the new level after it has held for the debounce interval. Polling at 1 kHz gives 1 ms resolution, which is fine against an 8 ms bounce. An edge interrupt with the same timestamp check saves wakeups in sleep, but the logic is identical.

C
// Checked every 1 ms tick. DEBOUNCE_MS must exceed worst-case bounce.
#define DEBOUNCE_MS 10

static uint32_t last_change_ms;
static uint8_t  raw_level, debounced_level;

void button_tick(uint32_t now_ms, uint8_t level)
{
    if (level != raw_level) {
        raw_level = level;
        last_change_ms = now_ms;
    }
    if ((now_ms - last_change_ms) >= DEBOUNCE_MS &&
        debounced_level != raw_level) {
        debounced_level = raw_level;
        on_button_event(debounced_level); // press or release
    }
}

Unsigned subtraction handles the 32-bit millisecond counter wrapping, which a signed comparison of absolute times does not. The failure mode to test is a worn switch that bounces for 25 ms. With a fixed 10 ms window it will double-trigger. Measure bounce on a scope or logic analyser across temperature and aged switches, then set the window above the measured maximum with margin, and re-check that press-to-action latency stays inside budget. Hardware helps here: a 10 kΩ pull-up with 100 nF to ground gives a time constant near 1 ms, and a Schmitt trigger input stops slow edges from retriggering. That RC network does not replace the software debounce, it shrinks the bounce the software has to survive.

Sensor: IIR filter and its delay

C
// First-order IIR, fixed point. alpha_q15 = 0.2 * 32768 = 6554.
static int32_t filt_q15;

int32_t iir_step(int32_t sample_q15)
{
    filt_q15 += ((sample_q15 - filt_q15) * 6554) >> 15;
    return filt_q15;
}

For white input noise, the output variance scales by alpha / (2 - alpha). At alpha = 0.2 that is 0.111, so RMS noise falls to about 0.33 of the input, roughly 1.3 LSB from 4 LSB. The step response reaches 63% in about 1/alpha samples, so 5 samples, or 5 ms at 1 kHz, and the group delay is (1 - alpha) / alpha samples, about 4 ms. That arithmetic is the trade-off in one line: halving alpha again would cut noise further but push delay past 9 ms.

A worked trace with a step from 1000 to 2000 counts at sample 10 shows why you cannot judge the filter by its steady state:

SampleRawFiltered (alpha 0.2)Note
910001000settled
1020001200first step
1120001360
1220001488
1420001681
1920001886about 90% after 10 samples

If the control loop needs the step recognised within 5 ms, this filter fails even though the noise number looks good. A 3-point median filter is the alternative for spikes: it rejects a single-sample glitch with at most one sample of delay, but it barely reduces white noise. A moving average of N samples reduces white noise by sqrt(N) and delays by (N - 1)/2 samples, so an 8-sample average at 1 kHz gives about 2.8x noise reduction for 3.5 ms delay, similar to the IIR but with a finite memory and a linear phase response.

Button No Yes Sensor Raw sample or edge Discrete or continuous? Stable for debounce window? Ignore, update timestamp Emit one event IIR or moving average Check group delay vs loop budget

How I would defend the numbers in the interview

State the budget first, then show the filter fits it. Button: 10 ms debounce plus up to 1 ms sampling gives worst-case 11 ms, inside 20 ms. Sensor: 4 ms group delay plus one sample of conversion time stays under a 10 ms sensing deadline. Then name the checks: inject a step and measure delay on a GPIO toggled in the loop, feed the ADC a shorted input to measure the noise floor before and after filtering, and run the button through a bounce simulator or a worn switch sample. If the signal turns out to be a fast transient rather than a slow level, I would drop the IIR, keep the median for spikes, and move the filtering into the control law where the loop gain already accounts for delay, rather than hiding lag in the driver.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-66Walk me through a non-blocking state machine for a sensor device that uses timeouts to move from init to run and to a fault state if the sensor stops responding?

The 90-second answer

I would make the state machine the only place that decides what the device does next, and make every state do a small amount of work per tick and then return. No state waits in a loop for hardware. Each state has an entry action, a periodic tick, a timeout, and a defined exit to either the next state, a retry state, or a safe state.

For a sensor and actuator device I would use IDLE, INIT, CONFIG, RUN, and FAULT, with RECOVER as a sub-path out of FAULT. INIT starts the peripheral and arms a deadline. CONFIG writes registers one step at a time, because a single I2C write can NACK or stretch the clock. RUN polls the sensor, checks a data deadline, and drives the output. Any error moves to FAULT, which puts outputs in a safe condition first, records the cause, and only then decides whether a retry is sensible.

The key is that time is data, not a delay call. The main loop calls sm_tick(now_ms) every iteration, or a task wakes every 1 to 10 ms and calls it. The machine compares now_ms with a deadline stored on entry. That keeps interrupts short, keeps the watchdog honest, and lets the rest of the firmware run while a peripheral is slow.

IDLE INIT CONFIG RUN FAULT RECOVER

A concrete implementation

A transition table keeps the logic auditable. The tick function only dispatches the current state and checks its deadline.

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

typedef enum { ST_IDLE, ST_INIT, ST_CONFIG, ST_RUN, ST_FAULT, ST_RECOVER } State;

typedef struct {
    State state;
    uint32_t entered_ms;
    uint32_t deadline_ms;
    uint8_t retries;
    uint8_t step;
    uint32_t fault_code;
} Sm;

static bool expired(uint32_t now, uint32_t deadline) {
    return (int32_t)(now - deadline) >= 0; /* wrap safe for 32-bit ms */
}

static void enter(Sm *s, State next, uint32_t now, uint32_t timeout_ms) {
    s->state = next;
    s->entered_ms = now;
    s->deadline_ms = now + timeout_ms;
    s->step = 0;
}

void sm_tick(Sm *s, uint32_t now) {
    switch (s->state) {
    case ST_IDLE:
        if (start_requested()) enter(s, ST_INIT, now, 200);
        break;
    case ST_INIT:
        if (periph_init_step()) enter(s, ST_CONFIG, now, 500);
        else if (expired(now, s->deadline_ms)) { s->fault_code = 1; enter(s, ST_FAULT, now, 0); }
        break;
    case ST_CONFIG:
        if (config_step()) enter(s, ST_RUN, now, 1000);
        else if (expired(now, s->deadline_ms)) { s->fault_code = 2; enter(s, ST_FAULT, now, 0); }
        break;
    case ST_RUN:
        run_step(now); /* poll sensor, update output, feed data age check */
        if (sensor_stale(now)) { s->fault_code = 3; enter(s, ST_FAULT, now, 0); }
        else if (stop_requested()) enter(s, ST_IDLE, now, 0);
        break;
    case ST_FAULT:
        outputs_safe(); /* first, every time, before any retry logic */
        log_fault(s->fault_code);
        enter(s, ST_RECOVER, now, 300);
        break;
    case ST_RECOVER:
        if (s->retries < 3) { s->retries++; enter(s, ST_INIT, now, 200); }
        else enter(s, ST_IDLE, now, 0); /* give up, stay safe, wait for explicit start */
        break;
    }
}

periph_init_step() and config_step() each advance one register or one bus transaction per call and return false until done. If the bus is busy, they return false and the deadline decides failure. That is the non-blocking contract: a state never spins on a flag, it either makes progress or times out.

Worked trace

Assume a 1 ms tick, INIT timeout 200 ms, CONFIG timeout 500 ms, RUN data deadline 1000 ms.

Time (ms)EventState beforeActionState after
0start requestedIDLEarm INIT deadline at 200INIT
40init step doneINITarm CONFIG deadline at 540CONFIG
120config step 2 of 4CONFIGwrite next register, returnCONFIG
540no ACK, deadline hitCONFIGset fault_code 2FAULT
541FAULT tickFAULToutputs_safe(), log, arm RECOVERRECOVER
542RECOVER tickRECOVERretries 0 to 1, re-enter INITINIT
600init and config succeedINITarm RUN deadline at 1600RUN
1600no new sensor frameRUNset fault_code 3FAULT

The trace shows the two decisions an interviewer will probe. First, FAULT does not retry directly. It forces a safe output state, because a retry that re-enables a motor or heater before the cause is known can be unsafe. Second, RECOVER has a bound. Three retries then IDLE means a permanently broken sensor does not cause a reset loop that starves other tasks and hides the fault from diagnostics.

Trade-offs and failure modes

A flat switch like the one above is easy to review and fits in a few hundred bytes of RAM. It gets messy past about eight states, where a table of function pointers or a generated state chart is easier to check for unreachable states. I would not use an RTOS task per state. That adds stack cost per task and makes the current state harder to log.

Timeouts need a real clock source. A uint32_t millisecond counter wraps every 49 days. The subtraction in expired() handles that, but only if timeouts stay well under 24 days, which they do here. Signed overflow in timeout arithmetic is a classic bug at -O2, so I keep all time math unsigned and cast only the difference.

Detection matters as much as recovery. I would expose state, fault_code, retries, and time in state through a debug command and a fault log in flash. If RUN keeps timing out at 1000 ms but the sensor datasheet promises 100 Hz output, the fault is likely a missed interrupt or a bus stuck low, not a slow sensor. The state machine tells you where to look, and the deadline values should come from the datasheet and measured bus time, not round numbers I invented.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-67How would you choose between return codes, asserts, fault handlers and logging for error handling in a peripheral driver, and when is each the wrong choice?

The 90-second answer

I split errors by who can act on them. A driver returns a code when the caller can recover. It asserts when the caller has a bug and continuing would corrupt state. It traps through a fault handler when the system cannot safely continue. It logs when the error is expected often enough that a human or a field diagnostic needs a trace, but the system keeps running.

That split matters because each mechanism has a different cost and a different failure mode in production. Return codes are ignored. Asserts disappear in release builds. Fault handlers stop the product. Logging fills memory, burns power and can block an ISR.

Assume a bare-metal or RTOS peripheral driver on a Cortex-M, called from task context, with a separate ISR layer. The driver does not own product policy. It reports facts and enforces its own contract.

C
// Checked on Cortex-M4, GCC 12, -O2. NDEBUG defined for release.
typedef enum {
    DRV_OK = 0,
    DRV_ERR_TIMEOUT,   // hardware did not respond, caller may retry
    DRV_ERR_BUSY,      // transfer in progress, caller may retry later
    DRV_ERR_INVALID,   // bad pointer or length, caller bug
    DRV_ERR_HW         // NACK, overrun, CRC mismatch
} drv_status_t;

drv_status_t i2c_write(uint8_t addr, const uint8_t *buf, size_t len)
{
    assert(buf != NULL && len > 0);        // contract: compiled out with NDEBUG
    assert(!in_isr());                     // driver is task-context only
    if (i2c_bus_busy()) return DRV_ERR_BUSY;
    if (!wait_ack(1000)) {                 // 1000 us timeout, from timer ticks
        log_event(LOG_I2C_TIMEOUT, addr);  // ring buffer, no printf
        return DRV_ERR_TIMEOUT;
    }
    return DRV_OK;
}

assert here checks a programming invariant, not a hardware condition. A null buffer or a call from an ISR will never fix itself by retrying. In debug builds it traps with file and line. In release builds it vanishes, so the code after it must still not crash on bad input from untrusted callers. That is why the public API also returns DRV_ERR_INVALID for lengths that can arrive from a parser or a command handler. Assert alone is not input validation.

MechanismUse forExampleCost and failure mode
Return codeRecoverable runtime error, caller decidesI2C NACK, SPI timeout, DMA busyZero cost if ignored, which is the risk. Caller must check every call.
AssertBroken contract, bug in our codeNull pointer, wrong state, len exceeds static bufferDebug trap only. Release build silently continues, so never use it for hardware errors.
Fault handlerUnrecoverable corruption or illegal operationHardFault on bad pointer, UsageFault on unaligned access, stack guard hitStops the device or resets it. Needs a handler that records context and does not loop.
LoggingDiagnosis of expected faultsTimeout count, retry count, first NACK addressRAM, flash wear if written to flash, timing jitter. Ring buffer of fixed size, dropped count incremented.

Choosing in practice

For a sensor read that times out once in ten thousand reads, return DRV_ERR_TIMEOUT and log the first occurrence with the register address. The application can retry, mark the sensor degraded after three failures, or power-cycle it. If the driver instead asserted, a flaky sensor would brick the product in the field. If it logged with printf from the driver, a 9600 baud UART would block for about 1 ms per character and blow a 1 kHz control deadline.

For a driver called with a buffer that overlaps the DMA descriptor, assert in debug and return DRV_ERR_INVALID in release. The overlap is a caller bug, but a field unit should not execute a DMA transfer into its own descriptor. The return code gives the caller a chance to reject the request without a reset.

Fault handlers sit below all of this. A HardFault handler on Cortex-M should read HFSR, CFSR, and the stacked PC and LR from the exception frame, store them in a no-init RAM location, and then reset or enter a safe state. It should not try to return from a bus fault caused by a bad pointer, because the same instruction will fault again. It also should not call the logging code that might have caused the fault. A common failure is a fault handler that calls printf, faults again, and locks up with no diagnostic left behind.

Yes No Yes No Yes No Error detected Can caller recover? Return code + optional log Is it our bug? Assert in debug, return invalid in release Can system continue safely? Return hardware error, degrade gracefully Fault handler: record context, reset

Two rules keep this honest. First, every return code needs a caller that branches on it. I check this with a wrapper macro in debug builds that warns on an unused result, and with static analysis in CI. Second, logging stays out of ISRs and out of the fault handler. The ISR sets a flag or writes one entry to a lock-free ring buffer. A low priority task drains it. If the ring fills, increment a dropped counter instead of blocking. That keeps worst-case ISR time bounded, which I verify by measuring the ISR with a GPIO toggle on a scope, not by reading the code and hoping.

When I review a driver, I look for the inverse mistakes: asserts on timeouts, silent returns on null pointers, printf in an ISR, and a fault handler that tries to recover from corruption. Each one turns a diagnosable fault into either a field reset with no evidence or a silent data error.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-68Why does a blocking UART printf risk missing a real-time deadline, and how do RTT and SWO avoid that?

The 90-second answer

A blocking printf to a UART waits for every byte to leave the chip. That wait is set by the baud rate, not by the CPU, so it can be milliseconds long and it cannot be bounded tightly enough for a short deadline. RTT and SWO move log bytes over the debug probe instead of a UART, and the firmware side is a short write into a buffer or a trace FIFO. The host does the slow work.

The one fact that decides it

At 115200 baud with 8N1 framing, each byte costs 10 bit times. A modest 60 character log line therefore costs:

60 * 10 / 115200 = 5.2 ms

If the task that prints has a 1 ms period, that single line overruns it by five periods. The CPU is idle for most of that time, waiting on the UART transmitter or its interrupt. printf also takes the stdio lock, so a second task or an ISR that tries to log can block on it, and formatting, especially %f on a core without an FPU, adds more unbounded time. None of that belongs in an ISR or a control loop.

What RTT and SWO do differently

RTT, from SEGGER, puts a control block in RAM. Firmware writes bytes into an up-buffer in RAM, and the host reads them over SWD or JTAG. No UART pin is used and the write returns as soon as the bytes are copied to RAM. If the buffer is full, the write can drop data or wait, depending on the mode you choose. For task logging I choose drop, and I count the drops.

SWO is the single wire trace output on the debug connector. The ITM in the Cortex-M core sends bytes from a stimulus port, the TPIU serialises them, and a SWO capable probe decodes them on the host. The firmware cost is one store per byte.

C
/* Cortex-M4, CMSIS Core headers */
#include "core_cm4.h"

void log_byte(uint8_t b)
{
    /* Stimulus port 0: drop if the trace FIFO is full, never spin in an ISR */
    if (ITM->PORT[0] & ITM_PORT_FIFOU_Msk) {
        ITM->PORT[0] = b;
    }
}

In practice I push a compact record from the ISR, such as a timestamp and an event id, into a small RAM ring. A low priority logger task drains that ring and writes it to RTT channel 0 with SEGGER_RTT_Write. The ISR never formats a string and never waits for a baud rate.

PathTransportFirmware cost per byteRisk to a deadline
UART printfTX pin at the baud rateFormatting plus a blocking transmitMilliseconds per line, plus stdio lock contention
RTTSWD or JTAG to the hostCopy into a RAM bufferBounded copy, data dropped if the host is slow
SWO and ITMSWO pin to a trace probeOne store to the stimulus portBounded store, byte dropped if the FIFO is full

Failure modes worth naming

RTT shows nothing when the probe cannot find its control block, usually because the section was stripped or placed outside the RAM the probe searches. SWO shows garbage when the trace clock configured in the probe does not match the TPIU prescaler, or when the core clock changed after the trace was set up. Both are setup faults I check on the bench, not reasons to fall back to printf in the timed path. A GPIO toggle on the same event, checked on a scope, confirms the event happened even if a log byte was dropped.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-69How would you retarget printf to a UART on a small Cortex-M MCU, support %f only where needed, and keep its flash cost and blocking time under control?

The 90-second answer

On a Cortex-M with GCC and newlib-nano I would not start by calling printf from the application. I would retarget the C library to a small transmit queue, keep floating point out of the default build, and add it back only for the one diagnostic build that needs it. That separation is what controls both flash and the worst case blocking time.

Retargeting means providing the syscalls newlib expects. For output the critical one is _write. The others (_read, _close, _lseek, _fstat, _isatty, _sbrk) can be stubs returning errors, except _sbrk if anything still allocates from the heap. If _write is missing, the link fails or, worse, semihosting silently takes over and nothing appears on the UART.

C
/* retarget.c, checked against arm-none-eabi-gcc 13, newlib-nano */
#include <stddef.h>
#include <stdint.h>
#include "uart_queue.h"

int _write(int fd, const char *buf, size_t count)
{
    if (fd != 1 && fd != 2) return -1;
    /* Returns bytes accepted. Never waits for the wire here. */
    return uart_tx_enqueue((const uint8_t *)buf, count);
}

int _read(int fd, const char *buf, size_t count) { (void)fd; (void)buf; (void)count; return -1; }
int _close(int fd) { (void)fd; return -1; }
int _lseek(int fd, long off, int whence) { (void)fd; (void)off; (void)whence; return -1; }
int _fstat(int fd, void *st) { (void)fd; (void)st; return -1; }
int _isatty(int fd) { (void)fd; return 0; }
void *_sbrk(long incr) { (void)incr; return (void *)-1; }

uart_tx_enqueue copies into a ring buffer in RAM and returns immediately. A UART TX interrupt or DMA channel drains it. If the queue is full, the policy is explicit: drop the log line and count the drop, or block with a timeout. Blocking forever in _write turns a full queue into a hung control loop.

Why blocking cost decides the design

At 115200 baud, 8N1, each byte costs 10 bit times, about 86.8 µs. A modest 64 byte log line therefore takes 5.6 ms on the wire. In a 1 kHz loop with a 1 ms period that is five missed periods if _write polls the TXE flag. Even at 921600 baud the same line costs 0.7 ms. Polling _write is only acceptable for boot messages before interrupts run, or for a fatal fault handler where the loop is already dead.

The queue changes the cost profile. Enqueueing 64 bytes is a memcpy of tens of cycles. The wire time still exists, but it overlaps with the control loop. The failure mode moves from missed deadlines to queue overflow, which I can measure with a dropped-line counter and a high water mark. For a 256 byte queue at 115200 baud, sustained output above roughly 11.5 kB/s cannot be kept up, so logging rate has to be throttled regardless of the queue size.

printf / snprintf _write TX ring buffer TX interrupt or DMA UART THR Full: drop and count

Floating point and code size

With --specs=nano.specs and -Os, integer-only printf on a typical STM32F4 build lands around 2 to 4 kB of flash for the formatting core, depending on which conversions are referenced. Adding %f pulls in the floating point formatter and decimal conversion routines. On the same build I have measured roughly an extra 10 to 20 kB, plus soft float helpers on a core without an FPU, and noticeably deeper stack use during conversion. Those numbers move with compiler and library versions, so I check them in the map file rather than trusting a datasheet figure.

The link control is explicit:

# Makefile fragment
CFLAGS += -Os -ffunction-sections -fdata-sections
LDFLAGS += --specs=nano.specs -Wl,--gc-sections -Wl,-Map=app.map
# Diagnostic build only:
# LDFLAGS += -u _printf_float

-u _printf_float forces the float formatter in. Without it, %f may print nothing or fail to link, which is a useful guardrail in production. I also keep printf out of ISRs entirely. Formatting is not reentrant in most small libraries, it can allocate or touch errno, and its stack depth is hard to bound. An ISR records a code and a few integers into a RAM log, and a low priority task formats them later.

For most sensor values I avoid %f even in diagnostics. Print scaled integers:

C
/* value = 3.14159f, print as 3.142 without float formatting */
long scaled = (long)(value * 1000.0f + (value >= 0 ? 0.5f : -0.5f));
printf("%ld.%03ld", scaled / 1000, scaled % 1000 < 0 ? -(scaled % 1000) : scaled % 1000);

That still uses a float multiply, but it avoids the formatter. On a Cortex-M0 or M3 without an FPU, even that multiply is a soft float call, so for a hot path I would convert in fixed point from the raw ADC or encoder counts instead.

ApproachFlash costBlockingUse it for
Polling _write to TXELowest, no queueFull wire time in callerBoot and fault handler only
Queue plus TX interruptQueue RAM, small ISREnqueue time onlyNormal logging at 115200 baud and above
Queue plus DMADMA channel, buffer alignment careEnqueue time onlyHigh rate logs, cache based cores need care
snprintf to buffer, then queueFormatter cost, no wire wait in formatFormat time, still boundedISR produced events formatted by a task
Integer scaled printAvoids float formatterSame as chosen transportSensor values in production
%f with _printf_floatLargest, plus soft float on no FPU coresSame transport, slower formatBench diagnostics only

Two failure modes catch people out. First, stdout buffering: newlib may buffer until a newline or until the buffer fills, so a log line without \n appears late or not at all. I set the stream unbuffered or always end lines with \n during bring up, then revisit it. Second, calling printf before clocks and the UART are configured, or from two contexts at once, interleaves bytes and corrupts the queue. The queue enqueue needs a short critical section or a single producer rule, and the UART init has to happen before the first log call, including from fault handlers that use a direct polling write to a known register address.

I would verify the result three ways: check app.map for _printf_float and the actual .text size, measure enqueue time with a GPIO toggle or cycle counter, and flood the queue in a test to confirm drops are counted rather than deadlines missed.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-70How would you make a Cortex-M firmware build reproducible across machines and prove a 2 KiB flash increase is real, not toolchain drift?

The 90-second answer

Pin the toolchain and the linker script, build from a clean checkout, and make CI prove the result. I record the exact compiler, for example arm-none-eabi-gcc 13.2.1, the CMake version, and the commit hash with every artefact. Two builds of the same commit in different directories must produce the same hash for the code sections. If they do not, I treat that as a build bug, not a cosmetic difference.

A CMake toolchain file keeps the flags from drifting between a laptop and CI:

CMAKE
# cmake/arm-none-eabi.cmake
set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_SYSTEM_PROCESSOR arm)
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
set(CMAKE_C_COMPILER arm-none-eabi-gcc)
set(CMAKE_CXX_COMPILER arm-none-eabi-g++)
set(CMAKE_ASM_COMPILER arm-none-eabi-gcc)
add_compile_options(-mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16)
add_compile_options(-Os -ffunction-sections -fdata-sections -Wall -Wextra -Werror)
add_compile_options(-ffile-prefix-map=${CMAKE_SOURCE_DIR}=. -Wdate-time)
add_link_options(-nostdlib -Wl,--gc-sections -Wl,-Map=firmware.map -Wl,--cref)

-ffile-prefix-map removes absolute paths from debug info, -Wdate-time rejects __DATE__ and __TIME__, and CI sets SOURCE_DATE_EPOCH from the commit time. Version comes from git describe at configure time, passed in as a macro, so the same commit always yields the same string.

The linker script is a standalone script, passed with -T, so it replaces the default script rather than extending it:

LD
/* firmware.ld */
MEMORY {
  FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256K
  RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 64K
}
SECTIONS {
  .isr_vector : { KEEP(*(.isr_vector)) } > FLASH
  .text : { *(.text*) } > FLASH
  .rodata : { *(.rodata*) } > FLASH
  .data : { *(.data*) } > RAM AT> FLASH
  .bss : { *(.bss*) *(COMMON) } > RAM
  _estack = ORIGIN(RAM) + LENGTH(RAM);
  ASSERT(ADDR(.bss) + SIZEOF(.bss) <= ORIGIN(RAM) + LENGTH(RAM), "RAM overflow")
  ASSERT(LOADADDR(.data) + SIZEOF(.data) <= ORIGIN(FLASH) + LENGTH(FLASH), "FLASH overflow for .data load image")
  ASSERT(ADDR(.rodata) + SIZEOF(.rodata) <= ORIGIN(FLASH) + LENGTH(FLASH), "FLASH overflow")
}

KEEP stops --gc-sections discarding the vector table. .data lives in RAM at runtime and in flash as a load image that startup code copies. The asserts compare the end of the last RAM section against the end of the RAM region, and the load address of .data against the end of flash, so an overflow fails the link instead of wrapping.

Proving a 2 KiB increase

I build the previous release tag and the new commit with the same pinned toolchain, then compare section sizes and the map file. Illustrative figures from a real regression:

SectionBaselineNewDelta
.text61,440 B62,464 B+1,024 B
.rodata8,192 B9,216 B+1,024 B
.data512 B512 B0 B
.bss12,288 B12,288 B0 B

Sorting the map by object file pointed at sensor_filter.o. A const double table of 256 entries had replaced a float table. Constant data lands in .rodata, so that change added 256 x 4 = 1,024 bytes there, and the double precision conversion code added about 1,024 bytes to .text. The alternatives were to keep the double table and spend the flash, switch to float, or compute the values at startup into RAM. I switched to float because the filter tolerance allowed it and the 1 kHz loop had no spare cycles for runtime generation. If accuracy had mattered more, keeping the table and accepting the budget would have been the right call.

When not to demand byte identical output

Exact hash equality is strict and useful for release artefacts, but it is brittle when a vendor library embeds absolute paths, when a signing step adds a timestamp to metadata outside the ELF, or when debug info legitimately differs between hosts while the code is identical. In those cases I hash only the loadable sections, for example by extracting .text and .rodata with objcopy, and I gate on a size budget instead. CI fails if flash exceeds 240 KiB of 256 KiB or RAM exceeds 60 KiB of 64 KiB, and it reports the largest growing symbols from arm-none-eabi-nm --print-size --size-sort. That catches real regressions without blocking a merge over a path string in debug info. For a signed release I still require full ELF equality, because the signature covers the whole file.

Two drift sources show up repeatedly. A toolchain upgrade can change alignment or inlining and look like a code regression, so I build the old tag with the new toolchain and record that delta separately. Absolute paths and build counters leak into the ELF through debug info and macros, so I build the same commit in two directories and compare hashes before accepting any build system change.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-71Your Cortex-M firmware is 18 KiB over flash budget: how would you use function sections, LTO, stripping and the map file to cut size without breaking the vector table?

The 90-second answer

I would start from the map file, not from flags. Build with -Wl,-Map=firmware.map,--cref and sort the output by size, then attack the largest contributors in order: dead code, then duplicate code, then metadata that does not need to ship. The flags that do that work are -ffunction-sections -fdata-sections at compile time, -Wl,--gc-sections at link time, -flto across translation units, and -Os instead of -O2 where speed is not proven to matter. Stripping comes last. It shrinks the ELF file, not the code that runs, so it never fixes a flash overflow on its own.

The vector table survives because the linker script keeps it explicitly. Without that, garbage collection can discard the startup object or the table itself, since nothing in C code calls it by name.

What each flag actually does

-ffunction-sections puts each function in its own .text.<name> section and -fdata-sections does the same for variables. Alone they change nothing about size. Paired with --gc-sections, the linker walks from entry points and kept sections and drops everything unreachable. That is how an unused driver, a printf variant, or a calibration routine disappears.

LTO goes further. With -flto at compile and link, the compiler sees across files, inlines small helpers, removes duplicate implementations, and can prove a function is dead even when a header declares it. The cost is build time and a harder debug experience, and it can change behaviour around function pointers and assembly. Anything referenced only from assembly, such as interrupt handlers listed in the vector table, needs to stay visible to the linker.

StepWhat it removesTypical effect on a 240 KiB image*
Baseline -O2, no sectionsNothing240 KiB
Add -ffunction-sections -fdata-sections -Wl,--gc-sectionsUnused drivers, unused library code218 KiB
Add -flto -OsCross-file duplicates, inlined wrappers, larger codegen196 KiB
strip + objcopy -O binary for the shipped imageSymbol table, debug sections from the ELFELF 310 KiB to 196 KiB, binary unchanged

*Hypothetical figures for a Cortex-M4 image with a large HAL, labelled as an example. Measure yours with arm-none-eabi-size -A firmware.elf.

Reading the map file

The map file lists every input section, its address, and its size. I look for three patterns: a single object file contributing tens of kilobytes, many small sections from one library, and alignment padding. Padding shows up as gaps between sections. A 256-byte aligned section in flash can waste up to 255 bytes per occurrence, which adds up with DMA buffers or tables placed for alignment.

Shell
arm-none-eabi-gcc -Os -ffunction-sections -fdata-sections -flto \
  -Wl,-Map=firmware.map,--cref,--gc-sections \
  -Wl,--print-gc-sections -o firmware.elf $(OBJS)
arm-none-eabi-size -A firmware.elf | sort -k2 -nr | head -20
arm-none-eabi-strip firmware.elf
arm-none-eabi-objcopy -O binary firmware.elf firmware.bin

--print-gc-sections prints what was collected, which catches the case where a handler you expected to keep was dropped.

Keeping the vector table intact

LD
MEMORY { FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256K }
SECTIONS {
  .isr_vector : {
    KEEP(*(.isr_vector))
    *(.text.Reset_Handler)
  } > FLASH
  .text : { *(.text*) *(.rodata*) } > FLASH
  .data : AT(LOADADDR(.text) + SIZEOF(.text)) { *(.data*) } > RAM AT > FLASH
}

KEEP stops --gc-sections from discarding the table. The table must sit at the flash origin the core expects at reset, or startup code must set VTOR before enabling interrupts. If the table moves, the first exception fetches from the wrong address and the part faults before main runs. I verify placement with arm-none-eabi-objdump -h firmware.elf and check that .isr_vector starts at 0x08000000 with the reset handler as its second word.

Two failure modes show up in practice. First, LTO or --gc-sections drops a handler that is only referenced from the table in a separate assembly file, because the linker never saw the reference. Marking the handler __attribute__((used)) or keeping the table section fixes it. Second, stripping the ELF and then trying to debug a field return leaves no symbols. I keep an unstripped ELF with the same build ID as the shipped binary, and only strip the artifact that goes to production programming.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-72Which layer should catch a sensor driver logic bug first, a host unit test with a mocked HAL or hardware-in-the-loop, and why?

The 90-second answer

A host unit test with a mocked HAL should catch it first. It runs in milliseconds on a PC, needs no board, and can force the exact failure, such as a NACK, a timeout or a short read, on every commit. Hardware-in-the-loop (HIL) runs the same code on a real board, so it is slower and scarcer. Reserve it for behaviour only real hardware can show, such as interrupt timing, DMA interaction and electrical faults.

LayerRuns onBest at catching
Unit test, mocked HALHost PCDriver logic, state machines, CRC, parsing, retry and timeout arithmetic
Simulation, such as QEMU or RenodeHost PC with a modelled MCU and peripheralsBoot flow, interrupt and driver interaction, long soak runs, injected faults
Hardware-in-the-loopReal MCU board with automated stimulusReal timing and jitter, DMA and cache effects, bus and power behaviour

Why the mock wins for logic

The driver calls a small HAL interface. In the host test, a fake implementation replaces the real one, so the test controls the hardware response instead of waiting for it.

C
/* fake_hal.c: linked only in host tests */
#include "hal.h"

static int nacks_left;

int hal_i2c_write(uint8_t addr, const uint8_t *buf, uint16_t len) {
    (void)addr; (void)buf; (void)len;
    if (nacks_left > 0) {
        nacks_left--;
        return -1;
    }
    return 0;
}

void fake_set_nacks(int n) { nacks_left = n; }
C
/* sensor_test.c */
void test_sensor_retries_then_fails(void) {
    fake_set_nacks(10);
    TEST_ASSERT_EQUAL(-1, sensor_read(&value));
    TEST_ASSERT_EQUAL(3, fake_write_count());
}

That test runs in under a second, runs in CI on every change, and can also advance a fake tick by 10,000 ms to hit a timeout boundary without waiting. A HIL rig might take seconds per case, needs a board and a power supply, and cannot easily make a sensor NACK exactly three times.

What the mock cannot prove

The fake encodes what you believe the hardware does. If you assume the sensor is ready immediately after reset but silicon needs 5 ms, the host test passes and the board fails. The mock also has no real interrupt latency, no DMA completion, no clock stretching and no signal ringing. Simulation sits between the two: it models the CPU and peripherals from the reference manual, so it can catch boot and interrupt interaction, but it still follows the documented behaviour rather than silicon errata.

Where HIL fits

Use HIL as a short smoke and timing suite on a release candidate. Check that a 1 kHz ISR still meets its deadline under load, that DMA buffers behave with the cache enabled, and that the device recovers from reset and brownout. If a logic bug escapes to HIL, add a host test that reproduces it with the fake HAL, so the next change is caught in milliseconds instead of on the rig.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-73Walk me through reviewing a peripheral driver shared between an ISR and a task for ISR safety, volatile misuse, blocking calls and reentrancy?

The 90-second answer

I review the driver as three contracts. The ISR contract: bounded time, no blocking, no allocation, no shared library state. The data contract: every variable shared with the ISR is a hardware register accessed through a volatile pointer, a single naturally atomic word, or protected by masking the interrupt that can change it. The peripheral contract: the driver has one owner at a time, or it serialises access explicitly, because most peripheral state machines are not reentrant even if the register writes look harmless.

If any of those fail, I reject the code before looking at style. A volatile flag does not make a multi-byte transfer atomic, and a mutex does not make a peripheral safe to call from an ISR.

What I look for in the code

This pattern fails all three contracts:

C
/* Checked against GCC 13 for Cortex-M4, -O2 */
volatile uint32_t rx_count;
uint8_t rx_buf[64];

void UART3_IRQHandler(void)
{
    rx_buf[rx_count++] = UART3->DR;      /* no bounds check */
    HAL_UART_Transmit(&huart3, &rx_buf[0], 1, 100); /* blocks in ISR */
    printf("rx %lu\n", rx_count);       /* reentrant library call */
}

void task_process(void)
{
    rx_count = 0;                        /* races with ISR increment */
    HAL_UART_Transmit(&huart3, rx_buf, rx_count, 1000);
}

rx_count++ is a read, modify, write sequence. The ISR can preempt the task between the read and the write, so the task clear can be lost or the ISR increment can overwrite it. volatile on rx_count forces each access to memory, it does not make the increment atomic. rx_buf is not volatile, so the compiler may assume the task does not change it asynchronously. In a loop such as while (rx_count < 64) { /* wait */ }, the compiler can hoist the load of rx_count out of the loop if it can prove no visible code changes it, even though the ISR does. That is the concrete -O2 failure, not a vague caching claim.

The HAL_UART_Transmit call polls the transmit flag, which can wait for a full byte time. At 115200 baud 8N1 that is about 87 µs per byte, and with a 100 ms timeout it can hold the CPU for 100 ms inside an interrupt. printf takes the C library lock and formats into a static buffer, so a task calling printf at the same moment corrupts both outputs.

The fix moves work out of the ISR and makes ownership explicit:

C
#define RX_SIZE 128u
static volatile uint8_t rx_buf[RX_SIZE];
static volatile uint32_t rx_head;   /* written only by ISR */
static volatile uint32_t rx_tail;   /* written only by task */
static volatile uint32_t overrun_count;

void UART3_IRQHandler(void)
{
    uint32_t next = (rx_head + 1u) & (RX_SIZE - 1u);
    if (next != rx_tail) {
        rx_buf[rx_head] = (uint8_t)UART3->DR;
        rx_head = next;
    } else {
        overrun_count++;            /* drop and count, never block */
        (void)UART3->DR;            /* discard byte to clear flag */
    }
}

uint32_t rx_available(void)
{
    return (rx_head - rx_tail) & (RX_SIZE - 1u);
}

The ISR now does one register read, one store, one index update. The task drains the ring. If the ring fills, the driver drops data and increments a counter the task can report, instead of overwriting unread bytes or blocking the interrupt. If this runs under FreeRTOS, the ISR would wake the task with the FromISR variant of the queue or event group API, not by calling a task API directly.

CheckQuestion I askFailure I expect to see
Blocking callsDoes the ISR call anything that waits, retries, takes a lock or allocates?HAL_UART_Transmit, HAL_I2C_Mem_Write, a non-FromISR queue send, malloc, printf, floating point on an FPU-less core
volatile useIs it on the hardware register pointer and on shared flags, and is it missing where a multi-byte value is shared?volatile on a local copy, volatile used as a lock, non-volatile buffer shared with the ISR, volatile on a struct that hides a torn read
AtomicityCan the ISR preempt between the read and the write of this variable?64-bit counters on a 32-bit core, count++, clearing a flag the ISR sets, read-modify-write on a shared control register
ReentrancyCan two contexts enter the driver at once, or can the same context reenter it?Static TX buffer in a shared HAL handle, a state machine with no owner, an ISR and a task both calling start_transfer
Priority interactionDoes a lower priority ISR share state with a higher priority ISR?A CAN ISR and a UART ISR both writing the same DMA descriptor or the same huart handle

Shared peripheral reentrancy

Peripherals fail in ways registers do not show. An SPI driver that sets chip select, writes the FIFO, then waits for transfer complete has a window where a second caller can change the clock phase, the buffer pointer or the chip select line. The result is a frame that parses on the logic analyser as two half frames. I look for a single owner flag or a queue of requests, and I check that the owner is released on every error path, including timeout and abort. If the ISR completes the transfer, the completion path must restore the peripheral to idle before signalling the task, otherwise the next request starts from a half configured state.

For shared state I prefer masking the specific interrupt over a global critical section, because a global section delays every interrupt. On Cortex-M, NVIC_SetPriorityGrouping sets how priority bits split into group and sub-priority, while __set_BASEPRI sets the BASEPRI threshold register that masks interrupts at or below a chosen priority. Those are separate operations. The masked window must be short enough to fit the jitter budget for the highest priority interrupt. If the window is a 64-byte memcpy, that is a design problem, not a critical section problem. Move the copy to the task and pass a pointer or a ring index instead.

How I prove it

I run the static analyser rules for ISR context, check that every function called from an ISR is on an allow list, and measure the ISR with a GPIO toggle and a scope or a cycle counter. I compare the measured worst case against the deadline for that interrupt, which I take from the system design rather than assuming a fixed microsecond budget. If the measured time is close to a byte time at the configured baud rate, the transmit poll is in there. I also force the failure: fill the ring, preempt the task mid drain, and transmit while receiving. The overrun counter must move and no frame may be silently corrupted. That test catches the races a code read misses, because the compiler at -O2 will exploit the missing volatile in ways that do not appear at -O0.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-74How would you design a non-blocking SPI peripheral driver with timeouts and a state machine so a busy-wait loop never stalls the main loop?

The 90-second answer

I would split the driver into three pieces: an ISR or DMA completion that only records an event, a poll() function the main loop or RTOS task calls every 1 ms, and a state machine that advances one step per call. The caller starts a transfer with start(), then does other work. poll() checks the current state, checks a deadline, and either moves on, finishes, or reports an error. No function spins on a hardware flag.

That structure matters because a busy-wait on a 10 MHz SPI transfer of 64 bytes takes about 51 µs on the wire, but a sensor that needs 20 ms to convert, or an I2C device that stretches the clock for 5 ms, would hold the CPU for the whole wait. At a 1 kHz control loop that is 20 missed cycles.

C
// Checked against C11, Cortex-M4 at 84 MHz, SysTick = 1 ms
typedef enum { ST_IDLE, ST_WAIT_DMA, ST_DONE, ST_ERROR } state_t;

typedef struct {
    state_t state;
    uint32_t deadline_ms;
    uint32_t timeout_ms;
    volatile bool dma_done;   // set only by the DMA ISR
    uint8_t *buf;
    size_t len;
    uint32_t errors;
} spi_drv_t;

bool spi_start(spi_drv_t *d, uint8_t *buf, size_t len,
               uint32_t timeout_ms, uint32_t now_ms)
{
    if (d->state != ST_IDLE) return false;
    d->buf = buf; d->len = len;
    d->dma_done = false;
    d->timeout_ms = timeout_ms;
    d->deadline_ms = now_ms + timeout_ms;  // unsigned wrap is safe below
    dma_start_tx_rx(buf, len);
    d->state = ST_WAIT_DMA;
    return true;
}

// Call every 1 ms from the main loop. Returns true when finished.
bool spi_poll(spi_drv_t *d, uint32_t now_ms, int *result)
{
    if (d->state != ST_WAIT_DMA) return true;
    if (d->dma_done) {
        d->state = ST_DONE; *result = 0; return true;
    }
    if ((int32_t)(now_ms - d->deadline_ms) >= 0) {  // wrap-safe compare
        dma_abort(); spi_reset_peripheral();
        d->state = ST_ERROR; d->errors++;
        *result = -1; return true;
    }
    return false;  // still in flight, caller does other work
}

The deadline uses unsigned subtraction, so it stays correct when the 32-bit millisecond counter wraps after about 49 days. The signed cast on the difference is the standard wrap-safe idiom for a timeout shorter than 2^31 ms.

DMA ISR sets flag now past deadline IDLE WAIT_DMA DONE ERROR Abort DMA, reset peripheral

A worked trace for a 20 ms timeout, polled every 1 ms:

t (ms)State before pollEventState after pollCaller sees
0IDLEspi_start()WAIT_DMAtransfer started
1 to 19WAIT_DMAno DMA flagWAIT_DMApoll() returns false
7WAIT_DMADMA ISR sets dma_doneDONEpoll() returns true, result 0
20WAIT_DMAno DMA flag, deadline hitERRORpoll() returns true, result -1

The second row is the point. Between polls the control loop, logger, and watchdog feed all run. The driver costs one flag check per millisecond, roughly 20 cycles, instead of thousands of cycles spinning.

ApproachCPU during a 20 ms waitFailure behaviourWhen I would use it
Busy-wait on flag100% of the coreHangs until flag sets, no timeout unless you add one inside the loopA 2 µs register read in a critical section
Interrupt plus blocking semaphoreBlocked task, other tasks runTimeout on the semaphore, but the task cannot do other work meanwhileA dedicated RTOS task with nothing else to do
State machine plus poll()About 0.1% (one check per ms)Timeout moves to ERROR, peripheral is reset, caller retries or faultsMain loop firmware, shared bus, or a task that also handles other peripherals

Timeouts need a value from the datasheet, not a guess. For a sensor conversion I take the maximum conversion time, add the worst-case bus time at the actual clock, then add margin. Example: 12 ms conversion plus 64 bytes at 400 kHz I2C (about 1.5 ms) plus 2 ms margin gives 16 ms, rounded to 20 ms. If the device stretches the clock beyond that, the driver aborts and resets the bus instead of waiting forever.

Failure modes I design for: the DMA complete interrupt never fires because the peripheral errored, so the timeout path must abort DMA and reset the peripheral, not just set a flag. A device NACKs or holds SDA low, so the ERROR state needs a bus recovery step (clock out 9 pulses on I2C, then a STOP) before the next start(). A caller starts a second transfer while one is in flight, so spi_start() returns false in any state other than IDLE. I count timeouts in errors and expose that counter, because a rising count at a specific temperature or voltage points at signal integrity rather than software.

One limit: this pattern does not help if the caller has nothing else to do and the transfer is short. For a 3-byte register read that finishes in 30 µs, the extra state and poll call add complexity for no gain. I keep busy-wait only for transfers under about 50 µs inside a critical section, and use the state machine everywhere else.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-75SDA is stuck low and SCL is free after a master reset mid-transfer: how do you clock the slave out and issue a STOP in code to recover the I2C bus?

The 90-second answer

A slave holds SDA low when it is mid-byte and waiting for the next SCL edge, and the master reset left it there. The fix is to take the I2C peripheral out of the picture, bit-bang SCL as an open-drain GPIO, clock the slave through the rest of its current byte, then issue a STOP so every slave resets its state machine. Only then do you re-enable the peripheral and probe the bus.

I2C is open-drain with pull-ups, so no device drives a line high. A device only pulls low. That is why clocking works: the master can force SCL low and release it, and the slave advances one bit per rising edge until it finishes the byte, sees the ACK/NACK bit, and releases SDA.

Preconditions to check first

Read both lines with the peripheral disabled. If SCL is also low, a slave is clock-stretching or a device is faulty. Clocking will not help, because the slave is holding SCL and will not accept edges. Wait for its timeout, typically 25 to 35 ms on many sensors, or power-cycle that device. If SDA is low and SCL is high or free, proceed with the 9-clock recovery.

C
/* Checked against a generic Cortex-M GPIO model. Adapt pin names. */
#define SCL_PORT GPIOB
#define SCL_PIN  6
#define SDA_PORT GPIOB
#define SDA_PIN  7

static void gpio_open_drain(uint32_t port, uint32_t pin, int low)
{
    /* BSRR/BRR style: write 1 to set (release), 0 to clear (drive low) */
    gpio_write(port, pin, low ? 0 : 1);
}

static int gpio_read(uint32_t port, uint32_t pin)
{
    return gpio_input(port, pin);
}

static void delay_half_period(void)
{
    /* 100 kHz recovery clock: 5 us per half period. Use a timer or
       calibrated loop, not a bare NOP loop across clock speeds. */
    delay_us(5);
}

int i2c_bus_recover(void)
{
    i2c_peripheral_disable();
    gpio_configure_open_drain(SCL_PORT, SCL_PIN);
    gpio_configure_open_drain(SDA_PORT, SDA_PIN);

    if (gpio_read(SCL_PORT, SCL_PIN) == 0) {
        return -1; /* SCL held low: clock stretching or short. Do not clock. */
    }

    /* Clock out up to 9 bits. A slave mid-byte needs at most 8 data
       bits plus the ACK bit. Stop early once SDA releases. */
    for (int i = 0; i < 9; i++) {
        gpio_open_drain(SCL_PORT, SCL_PIN, 1); /* SCL low */
        delay_half_period();
        gpio_open_drain(SCL_PORT, SCL_PIN, 0); /* SCL released, rising edge */
        delay_half_period();
        if (gpio_read(SDA_PORT, SDA_PIN) == 1) {
            break;
        }
    }

    /* STOP: SDA low while SCL high, then SDA released while SCL high. */
    gpio_open_drain(SDA_PORT, SDA_PIN, 1);
    gpio_open_drain(SCL_PORT, SCL_PIN, 0);
    delay_half_period();
    gpio_open_drain(SDA_PORT, SDA_PIN, 0);
    delay_half_period();

    gpio_configure_alternate_function(SCL_PORT, SCL_PIN, GPIO_AF_I2C);
    gpio_configure_alternate_function(SDA_PORT, SDA_PIN, GPIO_AF_I2C);
    i2c_peripheral_enable();
    return i2c_probe_all_addresses();
}

Worked trace

Assume the slave stopped after 3 bits of a byte, so 5 data bits plus ACK remain. The master does not know the count, so it clocks until SDA releases, capped at 9.

PulseSCL actionSDA sampledMeaning
1low then released0Slave shifts bit 4
2low then released0Slave shifts bit 5
3low then released0Slave shifts bit 6
4low then released0Slave shifts bit 7
5low then released0Slave shifts bit 8
6low then released1ACK/NACK bit done, slave releases SDA
7 to 9not needed1Early exit, STOP follows

At 100 kHz the 9 pulses take about 90 us, plus STOP. That is cheap compared with a bus timeout of 10 ms or a device power cycle.

Why STOP matters

Clocking alone leaves the slave at a byte boundary but still inside a transaction. Without STOP, the next START from the peripheral may be ignored or interpreted as a repeated START in the wrong state. STOP resets the slave to idle and releases any remaining drive. Some slaves also need the STOP to clear an internal timeout counter.

Failure modes I check after recovery

Symptom after recoveryLikely causeNext step
SDA still low after 9 clocksSlave is dead, shorted, or holding SDA for a different reasonPower-cycle the slave rail, check for solder bridge
SCL low before clockingClock stretching slave or SCL short to groundWait 35 ms and re-read, then power-cycle
Bus works once, then sticks againSlave resets on brownout during traffic, or master reset is too shortFix reset sequencing, add bus timeout in the driver
Recovery works on the bench but not in the productPull-ups too weak for bus capacitance, edges too slow at temperatureCheck rise time, aim for under 1 us at 100 kHz, consider 2.2 kΩ over 10 kΩ

I also add a driver-level guard: if a transfer times out with SDA low, run this recovery once and retry the transaction once. If it sticks again within a few transfers, log the address that was in flight and treat it as a hardware fault, not a software retry loop. That distinction is what keeps a flaky sensor from wedging the whole bus in the field.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-76On a shared SPI bus, what must you reconfigure before starting a transfer to a different peripheral that uses a different SPI mode?

The 90-second answer

Reconfigure the SPI controller for that device before you start, then assert that device's chip select. SPI has no address byte and no in-band negotiation, so the controller has no way to know the next peripheral wants a different mode. CPOL, CPHA and clock rate are controller settings, not per-device properties stored on the bus.

The rule is one transfer, one configuration: set CPOL/CPHA and the clock divider for the device you are about to talk to, enable the peripheral, pull its CS low, transfer, then pull CS high. Do that for every device, every time, even if the previous device happened to use the same mode.

Why the mode matters

CPOL sets the idle level of SCLK. CPHA sets whether data is sampled on the first or second clock edge. If the controller is left in mode 3 (CPOL=1, CPHA=1, SCLK idle high) and you talk to a mode 0 device (CPOL=0, CPHA=0, SCLK idle low), the SCLK level is wrong before the first byte and the device samples on the wrong edge. The usual symptom is every byte shifted by one bit.

ModeCPOLCPHASCLK idleSampled on
000lowfirst edge (rising)
101lowsecond edge (falling)
210highfirst edge (falling)
311highsecond edge (rising)

Code shape

Change the mode only while the peripheral is disabled or idle, not mid-frame. On STM32 parts that means clearing SPE, confirming BSY is clear, writing CR1 and the baud-rate prescaler, then setting SPE again.

C
typedef struct {
    uint8_t mode;      /* 0 to 3 */
    uint32_t max_hz;
    GPIO_TypeDef *cs_port;
    uint16_t cs_pin;
} spi_dev_t;

void spi_transfer(const spi_dev_t *dev, uint8_t *buf, size_t len)
{
    spi_reconfigure(dev->mode, dev->max_hz); /* SPE=0, wait BSY=0, set CPOL/CPHA */
    HAL_GPIO_WritePin(dev->cs_port, dev->cs_pin, GPIO_PIN_RESET);
    HAL_SPI_TransmitReceive(&hspi, buf, buf, len, 100);
    HAL_GPIO_WritePin(dev->cs_port, dev->cs_pin, GPIO_PIN_SET);
}

Use a separate GPIO chip select per device. That lets you assert only the selected device and leave the others high, which is the idle state SPI requires. Hardware CS pins often tie CS timing to the frame and do not give you the setup delay some devices need, so manual CS is the common choice on a mixed bus.

Check it on a logic analyzer: SCLK idle level should match the selected CPOL, and each byte should have exactly 8 clocks. If those two match the datasheet for that device, the mode configuration is correct.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-77Your RS485 link at 115200 baud 8E1 shows framing errors and occasional corrupted frames when two nodes transmit: how do you configure parity, stop bits and direction control, and debug it?

The 90-second answer

Set both ends to the same frame format first, then fix direction control. For a typical Modbus-style RS485 link that is 8 data bits, even parity, 1 stop bit (8E1) at a shared baud rate, with the driver-enable pin asserted only while the UART shift register and its last stop bit are still on the wire. Most framing errors I see are not parity at all. They come from a baud mismatch, a peer using 2 stop bits, or firmware dropping DE too early and truncating the last byte. Collisions come from two nodes driving at once because the turnaround delay is missing or the receiver is still enabled during transmit.

Assume a half-duplex pair, one controller and one or more slaves, no hardware flow control, and a transceiver with separate DE and /RE pins tied together as DE/RE. If your part ties them internally, the same timing rules apply to the single pin.

Configuration that has to match

On an STM32-style USART, parity and stop bits live in CR1 and CR2. The exact register names differ on other vendors, but the fields are the same idea.

C
// STM32H7 / STM32F4 style, 115200 baud, 8E1, RS485
void rs485_uart_init(USART_TypeDef *u, uint32_t pclk_hz) {
    uint32_t brr = (2 * pclk_hz + 115200) / 115200; // oversampling by 16, rounded
    u->BRR = brr;
    u->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_UE |
             USART_CR1_PCE;              // parity enable
    u->CR1 &= ~USART_CR1_PS;             // PS=0: even parity, PS=1: odd
    u->CR1 &= ~USART_CR1_M;              // M=0: 8 data bits (M1:M0 = 00)
    u->CR2 &= ~USART_CR2_STOP;           // STOP=00: 1 stop bit
    // STOP=01 would be 0.5 stop, 10 = 2 stop, 11 = 1.5 stop on STM32F4
}

Even parity means the parity bit is chosen so the total number of 1 bits in data plus parity is even. Odd parity makes it odd. The receiver recomputes it and sets PE (parity error) if it disagrees. Parity catches a single-bit flip in a byte. It does not resynchronise a link running at the wrong baud rate, and it does not replace a CRC in the protocol.

Stop bits are idle time after the last data or parity bit. One stop bit gives the receiver a full bit time to resynchronise before the next start bit. Two stop bits add margin for slow transceivers or a peer with a loose clock, at a cost you can compute. At 115200 baud one bit is 8.68 µs. An 8E1 frame is 1 start + 8 data + 1 parity + 1 stop = 11 bits, 95.5 µs on the wire. 8E2 is 12 bits, 104.2 µs. That 8.7 µs per byte decides whether a 256-byte frame fits a 25 ms polling window.

Direction control and the turnaround

RS485 here is half duplex. Only one node may drive A/B at a time. DE high puts the driver on the bus. /RE low puts the receiver on. Tie them so DE high also disables the local receiver, which saves you from hearing your own echo.

The sequence that prevents truncated bytes and collisions:

C
void rs485_send(uint8_t *buf, size_t len) {
    rs485_set_tx();                       // DE=1, /RE=1
    delay_us(5);                          // transceiver enable time, check datasheet
    uart_write(buf, len);                 // DMA or interrupt driven
    uart_wait_tc();                       // wait for TC flag, not just TXE
    delay_us(guard_us);                   // 1 char time at low baud, see below
    rs485_set_rx();                       // DE=0, /RE=0
}

TXE means the data register is empty and the next byte can be loaded. TC means the shift register is empty and the last stop bit has left the pin. Waiting for TXE and dropping DE truncates the final byte. That truncated byte looks like a framing error at the peer, because the peer sees a start bit with no complete frame.

Guard time after TC covers transceiver disable time and propagation across the cable. A common starting point is one character time, which at 9600 baud 8E1 is 1.15 ms and at 115200 baud is 95 µs. Measure it on a scope across A and B rather than guessing. If the bus sits at a valid idle differential for that interval before the next driver turns on, collisions drop sharply.

No Yes Request to send Assert DE, disable RX Wait enable delay Load bytes, wait TC Wait guard time Deassert DE, enable RX Wait for reply timeout Reply complete? Log timeout, stay in RX

Debugging framing errors

Read the status flags in order. FE (framing error) means the stop bit sampled low. PE means parity mismatch. ORE means the receiver overran because firmware did not read fast enough. NE means noise. Clear them by the sequence the datasheet specifies, usually reading SR then DR, and log which flag fired with a byte counter. A counter that increments only on FE points at timing. A counter that increments on PE with a clean scope trace points at a format mismatch.

ObservationLikely causeCheck
---------
---------
---------
---------
FE on every byte, scope looks cleanBaud mismatch or stop-bit mismatchCompare measured bit time on scope with BRR calculation, confirm both ends use same oversampling
FE only after long idle, first byte badPeer wakes late, DE asserted late, or receiver not readyScope DE against TX, check wake-up delay and guard time
PE on some bytes, FE neverParity setting differs, or a bit flips on a long stubConfirm even vs odd on both ends, check termination and stub length
Corrupt frames only when two nodes activeBoth drivers on, or DE dropped earlyScope A/B differential, look for mid-frame contention and truncated last byte
ORE under load, no FE or PEISR or DMA too slow, buffer fullCheck ring buffer head and tail, raise priority or use DMA

Worked trace for a baud mismatch: you configure 115200, the peer runs at 9600 because its clock tree changed after a low-power wake. Bit time on the wire is 104 µs, you sample every 8.68 µs. The first few bits may decode, then sampling drifts by more than half a bit and the stop bit position lands on a data bit. FE fires on almost every byte. The fix is in the clock tree and the BRR value, not in parity.

For collisions, put a logic analyser or scope on A, B, DE and TX together. Healthy traffic shows one DE high at a time, a clean idle gap, then the next DE. Collision traffic shows overlapping DE signals, a differential voltage that collapses toward zero mid-frame, and a peer that reports FE or a CRC failure on that frame only. That pattern separates a wiring or termination fault from a protocol fault. Check 120 Ω termination at both physical ends of the bus, biasing resistors so the idle bus is not floating, and stub length. A floating idle bus makes receivers chatter and invent start bits.

When the link is clean, lock the settings in one place, assert them at init, and add a startup self-test that sends a known pattern to a loopback or a peer and counts FE, PE and ORE over a fixed window. If those counters stay at zero for 10,000 frames at temperature extremes, the configuration and turnaround are right.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-78Your 16 MHz MCU must talk to a PC at 57600 baud using 16x oversampling: how do you calculate the baud error from the divider and clock tolerance, and decide between the internal RC oscillator and a crystal?

The 90-second answer

I would calculate the error the divider forces first, then add the clock tolerance on top of it. The oscillator choice only matters after that arithmetic, because a crystal cannot fix a bad divisor.

For oversampling OS, usually 16 on most UARTs:

divisor = round(f_uart / (baud * OS))
actual_baud = f_uart / (OS * divisor)
quantisation_error = (actual_baud - baud) / baud

Worst-case total error is quantisation error plus clock tolerance, taken with signs aligned so they add. A receiver resynchronises on the start bit and samples near the middle of each bit, so error accumulates across the frame. For a 10-bit 8N1 frame I want the total under about 3 percent, and I treat 5 percent as the practical limit where framing errors start appearing.

Worked example: 16 MHz, 57600 baud, 16x

C
// Checked in a bring-up script, not on the target.
uint32_t divisor = (16000000u + (57600u * 16u) / 2) / (57600u * 16u); // 17
float actual = 16000000.0f / (16.0f * (float)divisor);                 // 58823.5
float quant_err = (actual - 57600.0f) / 57600.0f;                      // +2.12%
Clock sourceToleranceQuantisationWorst-case totalVerdict
Internal RC±2% over temp and voltage+2.12%+4.12%Marginal, expect framing errors at extremes
Crystal, 50 ppm total±0.005%+2.12%+2.13%Passes with margin

The RC figure is a typical datasheet number for a factory-calibrated internal oscillator. I would use the exact figure from the part I am designing with, over the full temperature range, not the 25 C typical. The crystal figure includes initial tolerance, temperature drift and aging, and at 50 ppm it is negligible next to the quantisation term.

That table is the decision. With RC, the divider already uses up 2.12 percent and the oscillator can add another 2 percent in the same direction, which leaves almost no margin for the PC end, cable noise or a slow rising edge. With a crystal, the total is essentially the quantisation error alone and the link has room to spare.

When RC is still the right answer

At 9600 baud from the same 16 MHz clock, the divisor is 104 and the quantisation error is +0.16 percent. The RC tolerance then dominates at about ±2 percent total, which is comfortably inside budget. I would ship RC there and save the crystal, the load capacitors and the layout area. The pattern is that quantisation error grows as baud rises toward the clock frequency, because the divisor gets small and rounding to the nearest integer is a larger fraction of it. That is why the same oscillator that is fine at 9600 becomes marginal at 57600 and worse at 115200.

If I needed 115200 from this clock, I would not argue about the oscillator. I would check whether the part offers 8x oversampling, which gives a divisor of 17 and +2.12 percent at 115200, or a fractional baud generator, or a PLL output at 48 MHz that makes the 16x divisor land almost exactly. Changing the clock fixes quantisation. Changing the oscillator only fixes tolerance.

What I would verify

I would put a scope on the receiver pin and count framing errors over a long transfer at the temperature extremes, rather than trusting a short loopback test at room temperature. Loopback on the same MCU hides the problem because both ends share the same clock error. I would also confirm the host is crystal-referenced. If the host were RC-derived as well, its error would add to mine and even the crystal version would need rechecking.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-79Your device sleeps at 48 µA against a 5 µA budget: how would you audit GPIO leakage, regulator quiescent current and peripheral clocks to find and fix the excess?

The 90-second answer

Measure the sleep rail first, then isolate one domain at a time. A 48 µA reading against a 5 µA budget is rarely one fault. On a Cortex-M4 board I usually find three stacked contributors: a floating or back-powered GPIO at 15 to 30 µA, a regulator drawing 10 to 20 µA quiescent current at a 20 µA load, and a peripheral clock or flash domain that never entered its low-power state at 5 to 15 µA.

I put a current sense resistor or a Joulescope in series with the battery, remove the debugger, and log current while I change one thing per run. Debugger attached, a lit LED, or USB enumeration alone can add hundreds of microamps and hide the real fault.

Worked audit, hypothetical board, 25 °C, 3.3 V rail

StepChangeSleep current after
BaselineNothing changed, debugger detached48 µA
1Unused GPIOs to analog, no pull, outputs off19 µA
2Sensor rail switched off at load switch, its GPIOs to analog11 µA
3Buck regulator replaced with 1.2 µA Iq LDO for sleep rail4.6 µA
4Peripheral clocks gated, flash deep power-down, SysTick stopped3.8 µA

The arithmetic matters for the product case. At 3.8 µA average, a 2,000 mAh cell gives 2,000,000 µAh / 3.8 µA = 526,000 h before self-discharge dominates. At 48 µA the same cell lasts 41,600 h, about 4.7 years, and a coin cell is dead in months. That gap decides whether the fix is worth a board spin.

GPIO leakage. A floating CMOS input can sit near mid-rail and draw shoot-through current through its input stage. A pull-up to a sensor that is powered off is worse: current flows through the pull-up, then through the sensor ESD diode to its unpowered rail, and sometimes back through a shared ground. I set every unused pin to analog mode, which disconnects the input buffer on STM32 and similar parts, disable outputs, and remove pulls. For pins that must stay digital, I drive them to the rail that matches the external circuit or disconnect the external device and re-measure. Lifting one pin at a time with a hot-air station, or cutting a series resistor on a test board, identifies the offender faster than guessing.

Regulator quiescent current. Check the datasheet Iq at the actual load, not the headline number at 1 mA. Many bucks draw 15 to 30 µA Iq and lose efficiency below 100 µA load, while a good LDO draws 1 to 3 µA. Measure the regulator input current with its output unloaded, then with the MCU in STOP. If the output rail is only needed for the MCU, use the regulator enable pin or a load switch to shut the sensor rail down completely in sleep. Watch ceramic capacitor leakage and feedback divider current too. A 100 kΩ divider at 3.3 V draws 33 µA, which alone blows a 5 µA budget. Use 1 MΩ or higher, or switch the divider with a GPIO.

Peripheral clocks and domains. Gate every clock that sleep does not need: GPIO, DMA, ADC, timers, UART, SPI, I2C, and the HSI. Stop SysTick and rely on RTC wakeup. Put flash into deep power-down, keep only the RAM banks that must retain state, and stop DMA channels. A UART transmitter left enabled with TX low can also back-power a USB bridge through its protection diodes.

C
/* STM32L4-style sleep entry, checked against HAL docs */
void enter_sleep(void)
{
    GPIO_InitTypeDef gpio = {0};
    gpio.Mode = GPIO_MODE_ANALOG;
    gpio.Pull = GPIO_NOPULL;
    gpio.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3;
    HAL_GPIO_Init(GPIOA, &gpio);

    __HAL_RCC_GPIOA_CLK_DISABLE();
    __HAL_RCC_USART1_CLK_DISABLE();
    __HAL_RCC_ADC_CLK_DISABLE();
    __HAL_RCC_DMA1_CLK_DISABLE();

    HAL_SuspendTick();
    HAL_PWREx_EnableFlashPowerDown();
    HAL_PWREx_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON,
                            PWR_STOPENTRY_WFI, 0);
}

Failure modes to check before declaring victory. Leakage roughly doubles every 10 °C on some CMOS processes, so a board that passes at 25 °C can fail at 60 °C in an enclosure. Re-measure at temperature extremes. Also re-measure after wake: a clock tree that restores incorrectly, or a peripheral left in reset, can leave the device drawing milliamps until the next reset. Log sleep current, wake count, and wake reason in retained RAM so field returns can be compared against the bench trace.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-80If a battery sits close to the regulated voltage and the load sleeps most of the time, why does an LDO usually give longer battery life than a buck converter?

The 90-second answer

An LDO usually wins that case because its efficiency is set by the voltage ratio, Vout / Vin, and a battery close to the rail makes that ratio high. At 3.3 V from a 3.7 V lithium-ion cell, an LDO is about 89% efficient before quiescent current. A buck has no such fixed ratio, but its controller, inductor and feedback divider still draw current at light load. When the load sleeps at a few microamps, that overhead decides battery life.

Quiescent current is the key number. Many low-Iq LDOs draw 1 to 10 µA to ground. A typical buck draws 10 to 50 µA even with no load, unless it is a nano-Iq part in pulse-frequency modulation mode. Put a 5 µA sleep load behind a 25 µA buck and the regulator itself consumes five times the load. Put the same load behind a 3 µA LDO and the overhead is smaller than the load.

Dropout points the same way for a single-cell product. An LDO needs Vin >= Vout + Vdropout. A 3.3 V LDO with 150 mV dropout at full load stops regulating near 3.45 V. That is a real cost, and it is why the battery cutoff and the minimum operating voltage of the MCU have to be checked together. A buck can hold regulation to a lower input voltage, but that advantage matters less if the product spends most of its life asleep and the battery is sized for the LDO dropout.

CaseLDOBuck
3.7 V in, 3.3 V out, active loadAbout 89% idealAbout 85 to 90%
3.7 V in, 3.3 V out, 5 µA sleep loadIq often 1 to 10 µAIq often 10 to 50 µA
6 V in, 3.3 V out, active load55% ideal, rest becomes heatAbout 85%
Battery near emptyDrops out at Vout + VdropoutHolds regulation to lower input

Simple arithmetic, hypothetical figures

Sleeping for 10 s at a 5 µA load, the LDO with 3 µA Iq draws 8 µA from the battery. The buck with 25 µA Iq draws 30 µA. Over 10 s that is 80 µC against 300 µC, so the buck spends almost four times the charge doing no useful work. During a short 20 mA burst the two parts are close, about 89% against about 85%, and that burst is too brief to recover the sleep loss.

The rule I use is narrow. If the input stays close to the output and sleep dominates, pick the low-Iq LDO and verify dropout at maximum load and minimum battery voltage. If the input is well above the output, or the load stays active for long periods, pick the buck. If the rail must stay up while the battery falls below it, neither part is enough and the design needs a buck-boost.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-81How would you use ECC, CRC and periodic scrubbing to protect RAM in a safety-critical MCU, and what should firmware do on a single-bit versus a double-bit error?

The 90-second answer

Use hardware SECDED ECC on the SRAM for per-word correction, a CRC over larger persistent structures for detection beyond one word, and a background scrubber that reads every word so a corrected single-bit error is written back before a second upset lands in the same word. On a single-bit error, correct, log the address and syndrome, increment a counter, and keep running. On a double-bit error, the data is uncorrectable: do not use it, enter the fault handler, drive outputs to the safe state, preserve diagnostics, and reset or switch to a redundant channel depending on the safety architecture. The scrub interval and the error-rate thresholds are what turn that policy from a slogan into a defensible design.

Why three mechanisms

SECDED (single-error-correct, double-error-detect) protects each word at runtime. A common encoding for a 32-bit word is extended Hamming (39,32): 7 check bits, syndrome identifies the flipped bit, and a double error produces a syndrome that is neither zero nor a single-bit pattern. Many Cortex-M MCUs with ECC SRAM do this in hardware and raise a fault on a double error, with the faulting address and syndrome in a status register. Firmware still has to decide what happens next.

ECC alone does not cover a whole configuration block, a calibration table, or data copied to flash. A CRC-32 over a 4 KiB config region, checked at boot and after any update, catches multi-word corruption that a per-word code could miss if, for example, a DMA burst corrupts several words and the ECC counters are not checked. CRC detects, it does not correct, so a CRC failure means reject the block and fall back to a known-good copy or defaults.

Scrubbing closes the gap between the two. ECC corrects on read, but if firmware never reads a word, the error sits there. A second upset in the same word converts a correctable error into an uncorrectable one. The scrubber reads every location, forces the ECC check, and writes back corrected data.

C
/* Background scrub task, Cortex-M4 at 168 MHz, 256 KiB ECC SRAM */
#define SCRUB_WORDS_PER_TICK 64   /* spread the cost, see below */

void scrub_task(void *arg)
{
    static uint32_t idx = 0;
    for (;;) {
        for (uint32_t i = 0; i < SCRUB_WORDS_PER_TICK; i++) {
            volatile uint32_t *p = SRAM_BASE + idx;
            uint32_t v = *p;          /* read triggers ECC check/correction */
            if (ecc_corrected_since_last_read()) {
                *p = v;               /* write back the corrected value */
                log_ecc_event(ECC_SINGLE, (uint32_t)p, ecc_syndrome());
            }
            idx = (idx + 1) & SRAM_WORD_MASK;
        }
        vTaskDelay(pdMS_TO_TICKS(10));  /* 64 words per 10 ms */
    }
}

With 256 KiB there are 65,536 words. At 64 words per 10 ms the full pass takes about 10 seconds, and the bus cost is roughly 64 reads plus occasional writes per tick, well under 1% of a 168 MHz core. That interval is a design choice, not a default. If the part's soft-error rate is, say, 1,000 FIT per Mbit (hypothetical figure, take the real number from the MCU datasheet), a 2 Mbit array sees about 2,000 FIT, or one upset per 500,000 hours. A 10 second scrub makes a second upset in the same word before correction vanishingly unlikely. In a high-radiation or automotive deployment with a much higher rate, the same arithmetic drives a faster scrub or a smaller region for safety-critical variables.

Single versus double bit errors

EventECC resultFirmware responseData trusted?
No errorSyndrome zeroNothingYes
Single-bit upsetCorrected, syndrome matches one bitWrite back, log address and syndrome, increment counter, continueYes, after correction
Double-bit upsetDetected, uncorrectableFault handler, safe state, preserve diagnostics, reset or fail overNo
Triple-bit upsetMay be miscorrected as singleRely on CRC over the block and on error-rate monitoring to catch itNot guaranteed

That last row is the honest limit of SECDED. It is why the CRC and the counters matter. If single-bit corrections arrive at a rate far above the expected FIT rate, something else is wrong, such as a marginal supply rail, a failing cell, or a board-level fault. A sensible policy escalates: a handful of corrections per hour is logged, a burst (for example, more than 10 in a minute, tuned to the deployment) triggers a diagnostic fault and a controlled reset, because the next error may not be correctable.

For a double-bit error the handler must not retry the read and hope. The word is untrusted, and any value derived from it, including a pointer or a control output, is suspect. The handler should disable the outputs that depend on that memory region, record the address, syndrome, PC and a CRC of the surrounding block in a no-init section or in flash, and then reset. On the next boot, startup code checks the preserved record, runs the CRC over the affected region, and reports the event before entering the normal run state. If the system has a redundant channel, failover is preferable to reset, but only if the redundant channel's memory has its own ECC and its own scrubber.

Failure modes to name in the interview

Scrubbing in an ISR or at the highest priority will steal time from the control loop and can itself cause the deadline miss it was meant to prevent. Scrubbing only the heap and leaving .data and .bss untouched misses the variables that matter most. Checking the CRC over data that ECC has just corrected, without checking the ECC counters first, can hide a rising error rate. And a scrubber that writes back unconditionally on every pass wears the bus and can corrupt a word that is being updated concurrently, so the write-back should happen only when a correction was reported, and the region should be excluded while a DMA transfer targets it.

zero single bit double bit Read word ECC syndrome Use data Correct, write back, log Fault handler Safe state, save diagnostics Reset or fail over

The interviewer is looking for the thresholds and the reasoning behind them: scrub period derived from the soft-error rate, escalation on correction rate, and a double-error path that never trusts the data again.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-82How do you handle bad blocks and ECC on raw NAND, and why does that interface differ from a managed eMMC?

The 90-second answer

Raw NAND gives the host a page and block device with no safety net. You program a page, you erase a whole block first, some blocks arrive dead from the factory and more die in service, and data read back can flip bits. Firmware owns all of that: scan for factory bad blocks, keep a bad block table, check ECC on every page read, retire blocks that fail, and, if you want a filesystem, build the mapping and wear levelling yourself.

A managed eMMC moves that work inside the package. Its controller runs the FTL, ECC, bad block retirement and wear levelling, and the host talks MMC commands to logical block addresses. You still choose the right device, set its bus mode and check its health registers, but you do not implement the FTL.

Raw NAND geometry and why it hurts

Use a hypothetical example part to make the numbers concrete: 4 KiB data pages plus a spare area, 128 pages per block, so one erase block is 512 KiB. Real parts vary in page size, spare size and pages per block, and the datasheet for the exact part is the only source for those figures. You cannot overwrite a programmed page. The sequence is erase block, then program pages, and a page can only be programmed once per erase cycle. Endurance depends on cell type, vendor and temperature. SLC is typically rated in the tens of thousands of cycles, MLC in the low thousands, and TLC lower still. Check the datasheet for the part you are using rather than relying on a rule of thumb, because the rating decides how aggressive wear levelling must be.

Factory bad blocks are marked in the spare area of the first page of the block. For ONFI compliant parts the marker is byte 0 of the spare area, and it must be checked on page 0 and page 1 of the block only, not on every page. Some vendors use a different offset or additional markers, so the datasheet wins. Blocks also fail in the field from wear, read disturb and program disturb. Read disturb typically appears after many reads of neighbouring pages in the same block, so a block read heavily for scrubbing can corrupt a neighbour.

ECC lives in the spare area too. The controller or software computes a code over the page data and stores it beside the data. Common choices are BCH correcting a stated number of bits per codeword, or Reed-Solomon over the whole page. The host controller must be told the codeword size and step size. If you mismatch them, reads that should pass will fail, or worse, pass with miscorrection.

C
/* Example only: 4 KiB page, four 1 KiB BCH codewords.
   Checked against a generic ONFI-style part. The bad block
   marker is valid only on page 0 and page 1 of a block. */
int nand_read_page(struct nand *n, uint32_t block, uint32_t page,
                   uint8_t *data, uint8_t *spare)
{
    int rc = nand_hw_read(n, block, page, data, spare);
    if (rc != 0)
        return rc;
    if ((page == 0 || page == 1) &&
        spare[n->bb_marker_offset] != 0xFF)
        return -2; /* factory bad block marker present */
    for (int i = 0; i < 4; i++) {
        int corrected = bch_correct(&n->bch, data + i * 1024,
                                    spare + n->ecc_offset + i * 7);
        if (corrected < 0)
            return -1; /* uncorrectable: retire the block */
        if (corrected > n->bch_thresh)
            nand_retire_block(n, block); /* near limit, retire early */
    }
    return 0;
}

On a failed read you do not retry forever. You retire the block, copy any still readable pages to a spare block, and update the bad block table in a reserved area that itself needs two copies because it can also go bad. That table is the first thing a bootloader or MTD layer loads, before any filesystem.

Why eMMC is a different contract

An eMMC (JEDEC JESD84) presents 512 byte logical sectors. The host sends CMD17/CMD24 style reads and writes, or CMD18/CMD25 for multi block, and the internal controller handles page programming, erase, ECC and retirement. The host never sees a page, a spare area or a bad block marker. It does see device health in EXT_CSD registers, including pre EOL info and device life time estimate, and it can enable features such as reliable write, RPMB and discard.

AspectRaw NANDManaged eMMC
Host viewPage and block, erase before writeLogical sectors, overwrite in place
Bad blocksHost scans and retires, keeps BBTInternal, host sees only reduced capacity
ECCHost controller or software, per datasheetInternal, transparent to host
Wear levelling and FTLYou write it, or use MTD/UBIInternal, tuned by vendor
Performance controlDirect page timing, ONFI or vendor timingsBus mode HS200/HS400, cache, discard behaviour
Cost and flexibilityCheaper per bit, part specific timingsHigher cost, standard MMC interface
Failure visibilityPer page and per block detailCoarse, via EXT_CSD and timeouts

The trade off is control against work. Raw NAND lets you place a bootloader page exactly, guarantee erase latency for a real time task, and avoid a vendor FTL that may buffer writes unpredictably. You pay with a driver that must handle every failure mode above, plus a filesystem layer such as UBI if you want wear levelling and atomic updates. eMMC gives you a block device in an afternoon, at the cost of opaque write latency spikes during internal garbage collection and less visibility when a block is near end of life.

eMMC Raw NAND Host write to logical sector eMMC or raw NAND? MMC command to internal controller Internal FTL maps to free page Host FTL maps to free page Erase block if needed, program page ECC check on read, retire on failure Return success to host

Failure modes to name in the interview

Power loss during a raw NAND program can leave a page in an indeterminate state that reads as all 0xFF or passes ECC with wrong data on some parts, so metadata needs CRC and two copies. A grown bad block during a filesystem write must be handled by the FTL layer, not by returning an error to the application. On eMMC, a card that reports life time estimate at end of life, or a write that times out during internal erase, is the equivalent signal, and firmware should log EXT_CSD health periodically rather than waiting for the first failed write.

Pick raw NAND when you need deterministic placement, lowest cost, or a custom FTL for a bootloader and recovery image. Pick eMMC when the product needs a standard block device, faster bring up, and vendor managed endurance, and accept that you verify health through the standard registers instead of per page ECC counts.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-83Walk me through initializing an SD card and an eMMC device, including voltage windows, reset sequence and command timeouts?

The 90-second answer

Power the card or eMMC first, hold it in reset while rails settle, then run the identification commands at the lowest clock, usually 400 kHz for SD and 400 kHz for eMMC, and only raise the clock after the card reports its speed class. Every command gets a response timeout and a total initialization deadline. If either expires, you do not retry the same command forever. You re-issue CMD0, re-read the OCR, and after a bounded number of attempts you report the device absent or faulty.

Power VCC and VCCQ, release reset CMD0 GO_IDLE_STATE Read OCR: CMD8 for SD, CMD1 for eMMC CMD2 CID, CMD3 RCA, CMD9 CSD CMD7 select, set bus width and timing CMD6 switch function, verify EXT_CSD or switch status Raise clock, start data transfers

Voltage windows

SD and eMMC share the 3.3 V legacy window, but they do not share the later signaling window. A standard SD card runs VCC at 2.7 to 3.6 V, nominal 3.3 V. The host sends CMD8 with the 3.3 V check pattern 0x1AA and the card echoes it in R7 only if it accepts 2.7 to 3.6 V. If the echo mismatches, the card is SDIO, MMC, or a 1.8 V only device, and the SD path stops there. ACMD41 then returns the OCR. The host sets only the voltage bits it can actually supply and polls until the busy bit clears, with a 1 s ceiling in the SD Physical Layer Simplified Specification.

UHS-I changes the picture after initialization. The host and card exchange ACMD6 and CMD6 to switch to 1.8 V signaling, the host lowers VCCQ to 1.7 to 2.0 V, and only then may it select SDR50, SDR104, or DDR50. Doing the switch before the card has accepted it, or raising the clock before the voltage switch completes, produces intermittent CRC errors that look like a layout problem.

eMMC uses VCC at 2.7 to 3.6 V and a separate VCCQ at 1.7 to 2.0 V or 2.7 to 3.6 V. CMD1 returns the OCR, where bit 31 is the busy flag and bits 0 to 23 encode the voltage window in 0.1 V steps from 2.7 V. The host must pick a window inside both its own capability and the card's. CMD6 then selects bus width, high speed, HS200, or HS400, and CMD8 reads EXT_CSD to confirm what actually latched. A card that accepts CMD6 but reports the old timing in EXT_CSD has not switched, and running HS200 against it corrupts every block.

Reset sequence

For SD there is no hardware reset pin on most cards. CMD0 puts the card in idle state and clears the previous RCA. The host waits at least 1 ms after CMD0, sends CMD8, then loops ACMD41 with HCS set if the host supports SDHC. After the OCR busy bit clears, CMD2 reads the CID, CMD3 assigns a relative card address, CMD9 reads the CSD for block count and block length, CMD7 selects the card, ACMD6 sets 4-bit bus width, and CMD6 switches the function group. Each step depends on the previous one. Skipping CMD3 and using RCA 0, or sending CMD7 before CMD3, leaves the card unaddressed.

For eMMC, CMD0 also works, and devices with RST_n need a pulse of at least 1 microsecond low, followed by at least 1 ms before the first command, per the JEDEC eMMC spec. CMD1 is polled until the busy bit clears. Some parts need up to 350 ms for power-up, so a 1 s poll ceiling covers them without hanging boot. Then CMD2, CMD3, CMD9, CMD7, CMD6 for bus width, and CMD8 for EXT_CSD follow the same order as SD. The difference that bites in practice is CMD13. eMMC cards report ready-for-data in the R1 status, and the host should poll CMD13 after CMD6 and after any long write before issuing the next command.

Timeouts in code

Use a millisecond tick, not a cycle count, so the timeout survives clock changes. The table below uses values from the SD and eMMC specs and common host controller limits.

CommandExpected responseTimeoutOn expiry
CMD0none1 ms settle, then proceedre-issue once
CMD8, CMD1, ACMD41R3 or R7500 ms per try, 1 s total pollre-issue CMD0
CMD2, CMD3, CMD9R2 or R6500 msre-issue CMD0
CMD6, CMD7, ACMD6R1 or R6500 ms, 1 s for eMMC CMD6re-issue CMD0
CMD13 status pollR1, ready bit set500 ms per pollmark device busy, retry
Data read or writeR1 plus data CRC500 ms read, 250 ms write per block, longer for eraseabort, CMD13, retry block
C
/* Checked against SD Physical Layer Simplified Specification v9.00 and JEDEC JESD84-B51A. */
typedef enum { SD_OK, SD_TIMEOUT, SD_CRC, SD_ABSENT } sd_status_t;

sd_status_t sd_cmd(mmc_host_t *h, uint32_t cmd, uint32_t arg,
                   uint32_t *resp, uint32_t timeout_ms)
{
    uint32_t start = tick_ms();
    h->send_cmd(cmd, arg);
    while ((tick_ms() - start) < timeout_ms) {
        if (h->cmd_done()) {
            if (h->crc_error()) return SD_CRC;
            *resp = h->resp0();
            return SD_OK;
        }
    }
    return SD_TIMEOUT;
}

sd_status_t sd_init(mmc_host_t *h)
{
    uint32_t ocr = 0, deadline = tick_ms() + 1000;
    sd_cmd(h, 0, 0, &ocr, 10);              /* GO_IDLE_STATE */
    if (sd_cmd(h, 8, 0x1AA, &ocr, 500) != SD_OK) return SD_ABSENT;
    while (tick_ms() < deadline) {          /* ACMD41 poll */
        sd_cmd(h, 55, 0, &ocr, 500);
        if (sd_cmd(h, 41, 0x40FF8000, &ocr, 500) == SD_OK && (ocr & 0x80000000))
            return SD_OK;
    }
    return SD_TIMEOUT;
}

The unsigned subtraction in the loop handles tick wraparound. The 1 s deadline bounds the whole ACMD41 poll, so a missing card cannot stall boot. CMD0 is sent without checking a response, because the spec defines no R1 for it, and the 1 ms settle gives the card time to enter idle state before CMD8.

Failure modes worth naming

A card that answers CMD0 but never clears the OCR busy bit is usually undervolted or a counterfeit part with a slow flash init. A card that passes CMD8 but fails ACMD41 repeatedly often has VCCQ at the wrong level for UHS-I. An eMMC that accepts CMD6 and then fails every data CRC usually latched HS200 in EXT_CSD while the host stayed at 400 kHz, or the opposite. In each case the fix is to re-read the status register, CMD13 for eMMC and CMD6 switch status for SD, and compare what the card reports with what the host thinks it selected, rather than raising the clock and hoping.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-84What does a USB host request first during enumeration, and what does the device return before any other descriptor?

The 90-second answer

After reset the host does not know what the device is. It first issues GET_DESCRIPTOR(Device) on endpoint 0 and expects an 18-byte device descriptor. That reply gives the USB version, the maximum packet size for EP0, the vendor and product IDs, and how many configurations exist. Only then does it read the configuration, interface and endpoint descriptors, assign an address, and select a configuration. If that first reply is wrong, enumeration stops on every host.

The sequence for a full-speed device is:

  1. Bus reset, device at default address 0, EP0 enabled.
  2. GET_DESCRIPTOR(Device, 18) returns the device descriptor.
  3. Host assigns a unique address with SET_ADDRESS.
  4. Host repeats GET_DESCRIPTOR(Device) at the new address.
  5. Host reads GET_DESCRIPTOR(Configuration) with wLength=9 to learn wTotalLength, then again with that full length to get configuration, interface and endpoint descriptors together.
  6. Host selects a configuration with SET_CONFIGURATION, then reads string descriptors if the device advertises them.
StepHost requestDevice must returnTypical failure if wrong
Device descriptorGET_DESCRIPTOR(Device)18 bytes, bLength=18, bDescriptorType=1Host stalls EP0 or reports unknown device
AddressSET_ADDRESSACK, then move EP0 to new addressDevice answers at address 0 and 5 at once
ConfigurationGET_DESCRIPTOR(Configuration)wTotalLength equal to the actual bytes sentTruncated tree, host rejects the configuration
Set configurationSET_CONFIGURATION(1)ACK, enable endpoints in that configurationEndpoints stay disabled, transfers time out
StringGET_DESCRIPTOR(String, langID)UTF-16LE text, bLength even and correctHost shows no name, or on strict hosts fails
C
// C, checked against USB 2.0 spec section 9.6.1
// Packed: descriptor fields are byte streams on the wire, not C layout.
typedef struct __attribute__((packed)) {
    uint8_t  bLength;         // 18
    uint8_t  bDescriptorType; // 1 = DEVICE
    uint16_t bcdUSB;          // 0x0200 for USB 2.0, little endian on wire
    uint8_t  bDeviceClass;
    uint8_t  bDeviceSubClass;
    uint8_t  bDeviceProtocol;
    uint8_t  bMaxPacketSize0; // FS allows 8, 16, 32 or 64, not fixed at 64
    uint16_t idVendor;
    uint16_t idProduct;
    uint16_t bcdDevice;
    uint8_t  iManufacturer;
    uint8_t  iProduct;
    uint8_t  iSerialNumber;
    uint8_t  bNumConfigurations;
} usb_device_desc_t;

_Static_assert(sizeof(usb_device_desc_t) == 18, "device descriptor is 18 bytes");

Endpoints are declared in endpoint descriptors that follow each interface descriptor. EP0 is always a control endpoint and is not listed there. The type decides the transfer contract, and the choice is a trade-off between reliability, timing and throughput.

Endpoint typeUse it whenDo not use it when
Control, EP0Enumeration and class requests need reliable, ordered delivery with a stall on unknown requestsYou need bulk data throughput. Control transfers are short and host driven.
BulkLarge data with no timing need, for example CDC data or mass storage. Host retries errors, so data arrives intact but with no latency bound.A sample must arrive every millisecond. Bulk gives no periodic guarantee, so a busy host can delay it indefinitely.
InterruptSmall periodic data, for example HID reports. Host polls at bInterval, so latency is bounded by that interval.You need high throughput. Polling overhead and small packets waste bandwidth, and on full speed the interval cannot be below 1 ms.
IsochronousAudio or video where a constant rate matters more than a lost packet. Bandwidth is reserved and data may be dropped, with no retry.Any byte must arrive intact, for example a firmware image or a file. Dropped packets are never resent.

Speed also restricts the choice. Low-speed devices may only use control and interrupt endpoints. Declaring a bulk or isochronous endpoint on a low-speed device makes the configuration invalid, and the host rejects it even if the transfer code works in a loopback test. On full speed, bulk and isochronous are allowed, and EP0 packet size may be 8, 16, 32 or 64 bytes. The stack buffer and the descriptor must agree.

Bus reset GET_DESCRIPTOR(Device, 18) 18-byte device descriptor SET_ADDRESS(5) GET_DESCRIPTOR(Configuration, 9) wTotalLength = 32 GET_DESCRIPTOR(Configuration, 32) Config + interface + endpoint descriptors SET_CONFIGURATION(1) Host Device EP0

Debugging across hosts. Windows, Linux and macOS follow the same spec, but they surface failures differently and some are stricter about fields others ignore. Linux with lsusb -v and dmesg prints the descriptor dump and the exact stall. Windows Device Manager shows Code 43 when the descriptor set is inconsistent, and Wireshark with USBPcap shows which GET_DESCRIPTOR was stalled. macOS System Information shows speed and current draw, which catches a device that misreports its draw.

Current is a common mismatch. In the configuration descriptor, bMaxPower is in units of 2 mA, so 500 mA is written as 250, not 500. A device that writes 500 there claims 1000 mA, exceeds the bus-powered limit, and some hosts refuse to configure it.

When a device enumerates on one host and not another, check in this order: bLength and wTotalLength match the bytes actually sent, EP0 bMaxPacketSize0 matches the buffer the stack uses, string descriptor indices point to real strings or are zero, endpoint types are legal for the device speed, and the device stalls unknown control requests instead of returning garbage. A logic analyser on D+/D- or a USB protocol analyser settles which request was stalled, which is faster than guessing from the host error alone.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-85Your product must stream 2 Mbps over WiFi with 20 ms latency and also support BLE, using a co-processor: when do AT commands win over a native driver, and where do they break down?

The 90-second answer

AT commands win when the coprocessor is a certified module, the data rate fits the AT transport, and you need to ship without owning a radio stack. They lose when throughput, latency, or deterministic control is the product. For a 2 Mbps stream with a 20 ms latency budget, AT over UART is out on arithmetic alone. AT over SPI can move the bytes, but parsing text responses, handling unsolicited messages, and recovering from a wedged coprocessor still put a ceiling on jitter and on how fast you can react to a disconnect.

Assume a host MCU talking to a WiFi/BLE coprocessor such as an ESP32 running ESP-AT, a CYW43xx, or a Bluetooth controller in HCI mode. The split is not AT versus native in the abstract. It is who owns the stack, who owns the buffers, and who can be updated when a CVE or a certification issue lands.

Where AT breaks down, with numbers

UART at 921600 baud 8N1 sends 10 bits per byte on the wire (start bit, 8 data bits, stop bit, no parity). Payload rate is therefore 921600 / 10 = 92160 bytes per second, about 92 kB/s or 0.74 Mbps. A 2 Mbps payload needs 250 kB/s before any transport overhead. That is 2.7 times the UART capacity, so the link saturates even with zero AT text overhead. With AT framing, echo, and OK responses, usable payload is lower still. A transport that can carry the stream needs raw capacity comfortably above 2 Mbps to leave room for headers, retransmissions, and flow control stalls, which is why SPI, SDIO, or USB enters the discussion.

Text framing makes the problem worse on a faster transport. An AT+... command plus echo plus OK or ERROR is tens of bytes per transaction, and many AT firmwares serialize commands: one outstanding command, a timeout that can run from hundreds of milliseconds to seconds depending on the command, and a parser that must distinguish a command response from an unsolicited +IPD or +BLE... notification arriving mid-response.

A native driver moves binary frames. With HCI over UART, the host sends ACL packets with a 4-byte header and gets completion events from the controller. With WiFi over SDIO or SPI, the vendor driver (for example the CYW43xx fullMAC or a vendor ESP host driver) owns reassembly, retries, and rate control, and the host sees sockets or a netif. That is how you hold latency under 20 ms while the radio retries at the MAC layer. AT hides that layer, so a retry storm looks like a slow AT+CIPSEND and you cannot tell congestion from a dead peer.

DimensionAT commandsNative driver
TransportUART common, SPI/SDIO on some modulesSPI, SDIO, USB, HCI UART/SPI
Practical throughputUART 921600 8N1: 92 kB/s payload maximum. SPI AT: a few Mbps, vendor dependentSDIO/SPI: 10 Mbps and up, limited by radio and host CPU
Latency controlCommand timeouts in hundreds of milliseconds to seconds, unsolicited messages interleavedEvent timestamps, per-packet completion, flow control credits
Stack ownershipCoprocessor firmware, closedHost or vendor library, source or binary you can patch
CertificationModule certification often carries over if you stay in AT modeHost stack changes can require retest, depends on module grant
Failure recoveryReset coprocessor, rejoin, reissue commands, ambiguous stateReset controller, reinit HCI, replay connection state from host
Update pathFlash coprocessor through its vendor download mode, host unchangedUpdate host library, sometimes both sides must match

How I would implement each, and what fails

For AT, the failure mode I see most is a blocking parser. A task sends AT+CIPSEND=1460, waits for >, sends data, waits for SEND OK, and meanwhile a disconnect notification sits in the UART ring buffer. If the parser discards it while looking for SEND OK, the application thinks the socket is alive. The fix is a single UART ISR feeding a ring buffer, one parser task owning a state machine, and a queue of unsolicited events separate from command responses. Never call the AT send from an ISR or from a high priority control task.

C
/* AT side: parser owns the UART, application never touches it directly */
typedef enum { AT_IDLE, AT_WAIT_PROMPT, AT_WAIT_SEND_OK } at_state_t;

static void at_parser_task(void *arg) {
    at_state_t st = AT_IDLE;
    for (;;) {
        at_event_t ev = at_next_event(); /* from ring buffer, with timeout */
        switch (st) {
        case AT_IDLE:
            if (ev.type == EV_CMD_DONE) st = AT_WAIT_PROMPT;
            break;
        case AT_WAIT_PROMPT:
            if (ev.type == EV_PROMPT) { uart_write(cmd_buf, cmd_len); st = AT_WAIT_SEND_OK; }
            else if (ev.type == EV_UNSOLICITED) queue_unsolicited(ev); /* do not drop */
            else if (ev.type == EV_TIMEOUT) fail_command(AT_ERR_TIMEOUT);
            break;
        case AT_WAIT_SEND_OK:
            if (ev.type == EV_SEND_OK) { complete_command(); st = AT_IDLE; }
            else if (ev.type == EV_UNSOLICITED) queue_unsolicited(ev);
            break;
        }
    }
}

For native HCI, the equivalent risk is buffer accounting. The controller advertises a number of ACL buffers. If the host sends faster than the controller drains them, packets are dropped silently unless you track Number_Of_Completed_Packets events and stop at zero credits. A worked trace for a disconnect looks like this:

TimeHost sendsController eventHost action
0 msACL data, handle 0x0040Decrement credit count
3 msNumber_Of_Completed_Packets, handle 0x0040Increment credit, refill queue
40 msDisconnection_Complete, reason 0x08Tear down L2CAP channel, notify app, do not reuse handle until new connection
41 msCommand_Status for next commandOnly then issue new HCI command on that handle

That trace is impossible to reproduce with AT, because the disconnect arrives as text at an unknown point in a command exchange and the handle state lives inside the coprocessor.

Decision rule I would defend in review

Pick AT if the stream is under about 100 kB/s sustained, latency tolerance is hundreds of milliseconds, the module is certified and you cannot retest, and the team is small. Pick native if you need sustained megabits, latency under 50 ms, per-packet control, or a host side stack you can audit and patch. A hybrid is common: AT for provisioning and fallback, native for the data path, with a hardware reset line and a boot mode pin wired so the host can recover a coprocessor that stops answering AT at all. That reset line is not optional. Without it, a wedged AT firmware needs a power cycle you do not have in the field.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-86Your firmware has a 1 ms control loop, a 100 ms sensor poll and occasional UART logging: how would you decide between bare metal and an RTOS?

The 90-second answer

I would list the deadlines first, then check whether any work blocks. Bare metal is a superloop: one main loop calls each task in turn, and interrupts handle the time critical parts. An RTOS adds a scheduler that switches between tasks by priority and lets a task block on a queue or a peripheral without stopping the others.

For this product the control loop runs every 1 ms and must finish in about 20 microseconds. The sensor poll runs every 100 ms and waits for I2C. Logging happens occasionally and waits for UART. The sensor and logging tasks block for milliseconds. That blocking is the main reason to consider an RTOS. In a superloop, a blocking I2C read or a UART print would delay the next control iteration unless both drivers are rewritten as non-blocking state machines.

FactorBare metal superloopRTOS
LatencyLoop time sets latency. If each slice is short, control jitter stays low.Priority sets latency. A high priority control task preempts lower tasks.
Blocking I/OMust poll or use interrupts and state machines. Easy to miss a deadline if a driver blocks.A task can block on a queue or semaphore while other tasks run.
PowerSleeps when the loop has nothing to do. No tick to wake the core.Can sleep in tickless idle, but a regular 1 kHz tick wakes the core every millisecond.
Complexity and RAMSmall code and RAM footprint. Scheduling is implicit in loop order.Needs task stacks, queues and scheduler code. On a 64 KiB RAM Cortex-M4, three tasks of 512 words each fit easily.

How the superloop would look

C
// Bare metal, Cortex-M4 at 168 MHz. Control runs from a timer ISR.
volatile uint8_t control_due = 0;

void TIM2_IRQHandler(void) {
    control_due = 1;
    // Clear the timer flag here.
}

int main(void) {
    init_clock_and_peripherals();
    for (;;) {
        if (control_due) {
            control_due = 0;
            run_control_loop(); // Must finish in < 20 us.
        }
        sensor_state_machine_step(); // One I2C step, never a full blocking read.
        log_state_machine_step();    // Queue bytes to UART DMA, then return.
        if (nothing_due()) {
            enter_sleep(); // Woken by timer, I2C or UART interrupt.
        }
    }
}

This works if sensor_state_machine_step and log_state_machine_step each return within a few tens of microseconds. I would measure that with a GPIO pin toggled at the top and bottom of the loop and checked on a scope. If the worst case loop time stays below about 200 microseconds, the 1 ms deadline has margin.

How the RTOS version changes the trade-off

C
// FreeRTOS sketch. Priorities follow deadlines, highest number wins.
xTaskCreate(control_task, "ctrl", 256, NULL, 3, NULL); // 1 kHz
xTaskCreate(sensor_task,  "sens", 512, NULL, 2, NULL); // 100 Hz, blocks on I2C
xTaskCreate(log_task,     "log",  512, NULL, 1, NULL); // Occasional, blocks on UART
vTaskStartScheduler();

The sensor task can block waiting for I2C and the log task can block waiting for UART. The control task still runs every 1 ms because it has the highest priority. The cost is a context switch, roughly 5 to 10 microseconds on this class of part, plus the RAM for stacks and queues. That cost matters if the control budget were 5 microseconds. At 20 microseconds it is acceptable, and I would still measure it rather than assume it.

Power check with real numbers

Assume 12 mA active current and 2 microamps in stop mode. If the superloop is active 0.5 ms in each 10 ms cycle, average current is about 0.05 x 12 mA, or 600 microamps, plus the sleep current. An RTOS with tickless idle enabled can reach the same stop mode when all tasks block. With tickless idle disabled and a 1 kHz tick, the scheduler wakes the core every 1 ms for about 20 microseconds. That adds roughly 2 percent duty cycle, about 240 microamps, and can prevent the deepest sleep state. So power does not force bare metal. It forces a check of the tick configuration.

My decision for this product

With three activities and two blocking drivers, I would prototype the superloop first if the team is comfortable writing non-blocking I2C and UART drivers. It is simpler to debug and easier to prove timing. If the drivers already block, or more peripherals are planned, I would move to an RTOS and keep the control loop as the highest priority task or as a timer ISR. The deciding question is whether every slice can be made short and non-blocking. If the answer is no, the RTOS earns its overhead.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-87Why does a window watchdog need an independent clock, and how would you stop it resetting during a 2.5 s flash erase while still catching a hung task?

The 90-second answer

A window watchdog resets if it is refreshed too late, and on many parts also if it is refreshed too early. That early-refresh rule is what catches a supervisor that is spinning without doing work. I would clock it from the independent low-speed oscillator, not the main clock, so a clock-tree failure does not stop the timer. Each task sets a flag when it finishes a loop, a supervisor checks all flags, and only then refreshes inside the window. For a 2.5 s flash erase, I would erase in chunks and return to the scheduler between chunks, rather than blocking for the whole erase or stretching the timeout.

Assume a 32 kHz independent oscillator, a 100 ms supervisor period, and a 500 ms to 1000 ms window. Those figures are illustrative. I would take the real oscillator tolerance and register behaviour from the datasheet for the part in use.

Why the independent clock and the window

If the watchdog runs from the bus clock, a PLL or clock mux fault can freeze both the CPU and the watchdog. The independent oscillator keeps counting, so the reset still happens. The window adds the other direction of failure. An ordinary watchdog only catches a refresh that never comes. A window watchdog also catches a refresh that comes too soon, which is what a tight loop with no real work produces.

With a divide-by-32 prescaler on 32 kHz, one tick is 1 ms nominal. A 500 ms lower bound and 1000 ms upper bound give the supervisor room to run every 100 ms. A ±10% oscillator tolerance moves the real bounds to about 450 ms and 1100 ms, so task periods need to sit well inside that range. A 50 ms control loop does.

Task check-ins

No task refreshes the watchdog itself. Each task increments a counter after its work completes. Incrementing at the top of the loop would let a task that hangs mid-loop still look alive. The supervisor compares each counter with the previous value. If any counter has not moved, it skips the refresh and the window expires.

C
/* C11, hypothetical 32 kHz independent oscillator */
static volatile uint32_t heartbeat[NUM_TASKS];
static uint32_t last_seen[NUM_TASKS];

void control_task(void)
{
    for (;;) {
        control_step();
        heartbeat[TASK_CONTROL]++; /* after the work, not before */
        vTaskDelay(pdMS_TO_TICKS(50));
    }
}

void supervisor(void)
{
    for (;;) {
        bool all_alive = true;
        for (int i = 0; i < NUM_TASKS; i++) {
            uint32_t now = heartbeat[i];
            if (now == last_seen[i]) {
                all_alive = false;
            }
            last_seen[i] = now;
        }
        if (all_alive && in_window()) {
            watchdog_refresh();
        }
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

A stalled task is detected within two supervisor periods, 200 ms here, plus the remaining window. That is the trade-off against a longer window, which delays detection.

TimeControl counterSensor counterSupervisor action
0 ms104refresh
100 ms125all advanced, refresh
200 ms145sensor stalled, no refresh
1000 ms205window expires, reset

The erase problem, and the choice

A single blocking erase that polls for 2.5 s starves every task. The watchdog then fires even though the erase is healthy. The obvious fix is to stretch the timeout to 3 s, but that also stretches hang detection for the whole device and hides real faults during every erase.

Chunking avoids that trade-off. Erase one sector, return to the scheduler, let the supervisor refresh, then erase the next sector. Each chunk needs to finish well under the 500 ms lower bound. The erase task still increments its heartbeat between chunks, so a chunk that never returns is still caught.

Yes Yes No No Erase one sector Return to scheduler Supervisor checks heartbeats All advanced and in window? Refresh watchdog More sectors? Erase complete No refresh, reset on expiry

If the flash controller can run asynchronously, starting the erase and polling in short slices achieves the same result. I would only rely on that after confirming in the datasheet that the controller runs without CPU polling. I would not let the erase task refresh the watchdog directly, since that would mask a hang inside the erase loop.

Checks I would run on the bench

Force a task to stall and confirm the reset occurs and the reset-cause register records a watchdog reset. Force a supervisor that refreshes in a tight loop and confirm the early-refresh fault fires. Run a full 2.5 s erase and confirm no reset, with the supervisor refreshing between chunks. Those three traces cover the hung task, the spinning supervisor, and the legitimate long operation.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-88In rate-monotonic scheduling, which task gets the highest priority?

The 90-second answer

In rate-monotonic scheduling, the task with the shortest period gets the highest priority. The next shortest period gets the next priority, and so on. That ordering is the whole rule. You do not assign priorities by importance, by the order tasks were created, or by deadline alone.

The reason is simple. A task that repeats every 1 ms can miss its window many times while a task that repeats every 100 ms is still waiting for its first run. Giving the frequent task priority protects the frequent deadline. The infrequent task runs in the remaining time.

A concrete ordering

TaskPeriodRate-monotonic priority
Control loop1 msHighest
Sensor read10 msMiddle
Telemetry log100 msLowest

If the control loop needs 20 microseconds every 1 ms and the sensor task needs 800 microseconds every 10 ms, total utilisation is 0.02 + 0.08 = 0.10. The processor is busy 10 percent of the time, so the 100 ms telemetry task still gets long idle stretches. Starvation only becomes a risk when utilisation climbs close to 100 percent, because then the lowest priority task may never get a long enough run.

In code

On FreeRTOS, a larger priority number preempts a smaller one. Assign the numbers in period order.

C
/* Checked against FreeRTOS on Cortex-M, configMAX_PRIORITIES = 5 */
#define PRIO_CONTROL   4  /* T = 1 ms, highest */
#define PRIO_SENSOR    3  /* T = 10 ms */
#define PRIO_TELEMETRY 2  /* T = 100 ms, lowest */

xTaskCreate(control_task,   "ctl", 256, NULL, PRIO_CONTROL,   NULL);
xTaskCreate(sensor_task,    "sen", 512, NULL, PRIO_SENSOR,    NULL);
xTaskCreate(telemetry_task, "tel", 512, NULL, PRIO_TELEMETRY, NULL);

The same ordering applies to interrupts. A timer interrupt that fires every 1 ms should preempt a UART interrupt that fires far less often, so its NVIC priority number should be lower on Cortex-M, where a lower number preempts.

C
NVIC_SetPriority(TIM2_IRQn, 0);   /* 1 ms timer, preempts */
NVIC_SetPriority(UART3_IRQn, 2);  /* slower UART, preempted */

One limit is worth naming. Rate-monotonic uses period as the ranking. If a task has a period of 100 ms but a deadline of 5 ms, period alone ranks it last even though its deadline is tight. That case needs deadline-monotonic ordering instead, shortest deadline first. For the standard case where deadline equals period, rate-monotonic is the expected answer.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-89On an 8-bit MCU, how do you prevent torn reads of a 32-bit counter and multi-byte registers shared with an ISR without breaking interrupt latency?

The 90-second answer

On a bus narrower than the value, a multi-byte read is several instructions. An ISR can fire between them and change the value, so the reader assembles bytes from two different values. volatile does not fix this. It stops the compiler caching or reordering the access, it does not make the access atomic.

For a counter written only by an ISR, the usual fix is a short critical section: mask interrupts, copy the bytes to a local, restore the previous interrupt state, return the local. Keep the masked window to the copy, a handful of cycles, and restore the state you found rather than blindly enabling interrupts. That last point matters when the reader is itself called with interrupts already masked, or from another ISR.

C
/* 8-bit AVR, 16 MHz. Counter updated only in the encoder ISR. */
static volatile uint32_t enc_count;

uint32_t enc_read(void)
{
    uint8_t saved = SREG;
    uint32_t copy;

    cli();
    copy = enc_count;   /* 4 byte loads on an 8-bit bus */
    SREG = saved;       /* restores I bit, preserves flags we did not touch */
    return copy;
}

On Cortex-M the same shape uses PRIMASK or BASEPRI, and the compiler barrier is implicit in the barrier instructions. On Cortex-M3 and later you also have LDREX and STREX for a lock-free read-modify-write loop, but that only helps for RAM variables. It does not help for a memory-mapped peripheral register, and it does not help on Cortex-M0, which lacks exclusive access. There the critical section is the portable answer.

What a torn read looks like

Take a 32-bit counter at 0x0000FFFF on an 8-bit part, read low byte first. The ISR increments it to 0x00010000 after the second byte.

StepReader loadsCounter after ISRAssembled so far
1byte 0 = 0xFF0x0000FFFF0x000000FF
2byte 1 = 0xFF0x0000FFFF0x0000FFFF
3ISR fires, counter becomes 0x000100000x00010000-
4byte 2 = 0x010x000100000x0001FFFF
5byte 3 = 0x000x000100000x0001FFFF

The reader returns 0x0001FFFF, a value the counter never held. It is 65535 ahead of the true value. For an encoder that is a position jump. For a timestamp it is a spurious 65 ms step at 1 MHz. The error is largest at byte boundaries, which is why it shows up rarely and looks like noise.

Choosing the mechanism

SituationMechanismCost and limit
ISR writes, task or main reads, copy is 2 to 4 bytesMask interrupts, copy, restoreAdds interrupt latency equal to the copy. Four loads plus mask and restore is roughly 10 to 20 cycles, about 1 us at 16 MHz. Acceptable unless a higher priority ISR has a sub-microsecond deadline.
Value changes slowly relative to read rateRead twice, compare, retryNo latency added to interrupts. Needs a sequence counter or a version byte incremented by the writer, otherwise two reads can both be torn in the same way.
Cortex-M3 or later, RAM variable, frequent contentionLDREX and STREX loop, or C11 _AtomicLock-free only if the target supports it. Check __atomic_is_lock_free at runtime or ATOMIC_BOOL_LOCK_FREE at compile time. On 8-bit targets _Atomic uint32_t often lowers to a library call that masks interrupts internally, which is fine but you should know it is not free.
Hardware register that changes on read, such as a capture registerRead once inside the critical section, or use the peripheral's snapshot or buffer registerReading twice to compare is wrong here. The second read returns a new sample, not a check on the first.

The read-twice pattern needs care. A common version is a sequence counter: the writer increments it before and after the update, the reader retries if the two sequence values differ or are odd. That works for a struct shared between ISR and task. It fails if the writer is hardware itself, because hardware does not increment your sequence counter. For a timer capture register, use the timer's buffered capture or read the register with interrupts masked.

C
/* Sequence counter for a RAM struct shared with an ISR. */
static volatile uint32_t seq;
static volatile int32_t pos; /* written by ISR */

int32_t pos_read(void)
{
    uint32_t s1, s2;
    int32_t v;
    do {
        s1 = seq;
        v = pos;
        __asm__ volatile("" ::: "memory"); /* compiler barrier */
        s2 = seq;
    } while (s1 != s2 || (s1 & 1));
    return v;
}

The writer increments seq, writes pos, then increments seq again, with interrupts masked around the pair of increments if the ISR can preempt the writer. Without that, the sequence itself can be torn.

Failure modes I check for

Restoring the wrong state. sei() unconditionally in a function that was called with interrupts disabled re-enables them early and can corrupt a caller that was in its own critical section. Save and restore the status register or PRIMASK value.

Nested critical sections with different priorities. Masking all interrupts to protect a low priority shared variable also blocks a high priority ISR that has nothing to do with it. On Cortex-M, BASEPRI lets you mask only priorities at or below a threshold, which keeps a 1 kHz control ISR running while you protect data shared with a lower priority ISR. On 8-bit parts with a single global mask, that option does not exist, so keep the window short and measure the worst case added latency against the tightest ISR deadline.

Compiler reordering across the copy. The copy must be ordered with respect to the mask and restore. On most embedded compilers the interrupt control intrinsics act as barriers, but a hand written inline assembly sequence without a "memory" clobber can let the compiler move the loads outside the window at -O2. Test the generated assembly, not just the C.

Assuming a wide bus means atomic. A 32-bit load on a 32-bit Cortex-M is single cycle and atomic for aligned RAM. The same load from a peripheral on a slower bus, or a 64-bit value on a 32-bit core, is not. Alignment matters too. An unaligned 32-bit access can fault or split into two bus transactions depending on the core and the memory map.

How I would prove it

Force the race. Set the counter near a byte boundary, raise the ISR rate, and read in a tight loop while logging any value that is not monotonic. A torn read shows up as a backward jump or a jump larger than the maximum increment between reads. Then toggle a GPIO around the critical section and measure the masked window on a scope. If the window is 1 us and the fastest ISR deadline is 20 us, the trade is fine. If the window grows because the copy calls a library routine, that is the bug to fix, usually by copying bytes explicitly or by restructuring the data so the shared part fits in one register width.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-90Your firmware must run for six months without rebooting and allocates CAN frames, JSON buffers and log lines of varying sizes: how do you use static pools and slabs to prevent heap fragmentation and bound object lifetimes?

The 90-second answer

Ban general purpose malloc/free after init. Carve RAM at compile time into fixed size pools, one per object class, and allocate only from those pools. A 128 byte CAN frame pool, a 512 byte network buffer pool, a 64 byte log line pool. Each pool is an array of slots plus a free list. Allocation pops the head, free pushes it back. No splitting, no coalescing, no search. Allocation time is constant and fragmentation inside a pool is impossible because every slot is identical. Lifetime is bounded by ownership and a lease: every slot carries an owner tag and a generation counter, and a periodic sweep reclaims slots whose lease expired. If a pool is empty, allocation fails deterministically instead of corrupting the heap after month three.

That design only works if you size pools for worst case concurrency, not average load. Count the maximum number of objects that can be live at once, add margin for bursts, and prove it with a high water mark counter in production builds.

C
/* Checked against GCC 13 for Cortex-M4, -O2 */
#define POOL_SLOTS 32
#define SLOT_SIZE  128

typedef struct {
    uint8_t  data[SLOT_SIZE];
    uint16_t generation;
    uint8_t  owner;      /* enum: CAN_RX, NET_TX, LOG */
    uint8_t  in_use;
} slot_t;

typedef struct {
    slot_t   slots[POOL_SLOTS];
    int16_t  free_head;  /* index or -1 */
    uint16_t high_water;
    uint16_t alloc_count;
} pool_t;

void *pool_alloc(pool_t *p, uint8_t owner)
{
    if (p->free_head < 0) return NULL;   /* fail fast, never block */
    slot_t *s = &p->slots[p->free_head];
    p->free_head = s->generation;        /* reuse field as next link when free */
    s->in_use = 1;
    s->owner = owner;
    p->alloc_count++;
    if (p->alloc_count > p->high_water) p->high_water = p->alloc_count;
    return s->data;
}

In real code the next link is a separate int16_t next[] array so the generation counter survives free. The point stands: one array, one head index, no metadata interleaved with user data.

Why a slab beats a heap here

A slab allocator is the same idea with size classes. Instead of one pool per type, you keep pools for 32, 64, 128, 256 and 512 byte slots and round every request up to the next class. Internal waste is bounded: a 200 byte request wastes 56 bytes in a 256 byte slot, about 22 percent. External fragmentation, the heap splitting into unusable holes, cannot happen because a freed slot is always reusable for the same class.

ApproachAllocation costFragmentation over 6 monthsFailure mode
malloc/free on 32 KiB heapvariable, scans free listholes from mixed sizes, largest free block shrinksNULL at unpredictable time, or silent corruption
One pool per typeO(1) popnone within poolNULL when concurrency exceeds pool size
Slab with size classesO(1) pop from class poolbounded internal waste onlyNULL when class pool exhausted

Worked sizing example, hypothetical but labelled as such: a CAN gateway receives bursts of 24 frames during a fault storm. A 128 byte pool with 32 slots costs 4 KiB and covers the burst plus 8 spare slots. A heap would need to hold the same 24 frames plus JSON buffers and log lines, and after thousands of alloc/free cycles of 40 to 900 bytes the largest contiguous block can drop below 512 bytes even with 10 KiB free in total. The pool fails only if a 33rd frame arrives while all 32 are live, which is a design bug you can count and test.

yes no Request arrives Pool has free slot? Pop slot, stamp owner and generation Return NULL, count drop, log owner Use, then free or lease expires Sweep reclaims expired slots

Bounded lifetimes

Fixed slots alone do not stop a leak. A task that allocates a log line and never frees it will exhaust the pool in a week. Three mechanisms bound lifetime:

  1. Lease expiry. Each slot stores expiry_tick. A 10 Hz sweep in the background task frees slots past expiry and increments a leak_count per owner. A CAN frame leased for 500 ms that is still live after 2 s is a bug, not a slow consumer.
  2. Generation counter. Free increments the generation. A stale pointer held by a task fails the check ptr_generation == slot_generation instead of silently aliasing a new object. This catches use after free and double free, which a heap hides.
  3. Owner tag. On exhaustion you know which subsystem leaked because the drop counter is per owner. That turns a field failure into a reproducible test: flood the CAN bus, watch CAN_RX high water hit 32, fix the consumer.

When not to use it

Pools waste RAM when object sizes vary widely or concurrency is genuinely unbounded, for example parsing arbitrary length JSON from a host. There, a bounded arena that resets per request, or a streaming parser that never stores the whole document, fits better. If you cannot bound the maximum live count, you cannot size the pool, and pretending otherwise just moves the failure. The discipline is the sizing proof: worst case live count, high water mark in the field, and a drop counter that pages nobody at 3 a.m. because the pool simply said no.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-91Your doorbell register is volatile and you write the FIFO payload before it: why can the device still act on the doorbell first, and which barrier do you add before the doorbell write?

The 90-second answer

volatile stops the compiler from deleting, caching, or reordering the doorbell access itself. It does not stop the CPU store buffer or the bus from delivering that store before earlier payload stores. So the device can see doorbell = 1 while the last payload words are still in flight.

The fix on a single-core Cortex-M is a write barrier between payload and doorbell: write all payload words, execute __DMB(), then write the doorbell. __DMB() orders every memory access before it ahead of every access after it. Use __DSB() after the doorbell only if the next instruction must wait until the doorbell write has completed on the bus.

Assume a Cortex-M4, payload written to MMIO FIFO registers, doorbell is a separate MMIO register, and no DMA reads RAM directly. That keeps cache maintenance out of this problem.

C
/* CMSIS 5.x, Cortex-M4 */
#include "core_cm4.h"

typedef struct {
    volatile uint32_t fifo[64];
    volatile uint32_t doorbell;
} dev_regs_t;

#define DEV ((dev_regs_t *)0x40001000u)

void send_frame(const uint32_t *src, uint32_t n)
{
    for (uint32_t i = 0; i < n; i++) {
        DEV->fifo[i] = src[i];
    }
    __DMB();              /* payload stores reach the device first */
    DEV->doorbell = 1;
    __DSB();              /* optional: wait for doorbell completion */
}

What each tool actually does:

ToolCompiler reorderingCPU and bus reorderingTypical cost
volatile pointerPrevents elision and caching of that accessNoneOne store per access
Compiler barrier, asm volatile("" ::: "memory")Prevents reordering around itNoneNo instruction emitted
__DMB()Also a compiler barrierOrders prior stores before later storesA few cycles, drains store buffer
__DSB()Also a compiler barrierWaits for prior accesses to completeWaits for bus acknowledgement, tens of cycles

A worked trace shows the race. Without the barrier, the core issues payload stores, they sit in the store buffer, and the doorbell store takes a faster path to the peripheral bridge. The device starts reading and gets the previous frame or zeros in the tail. With __DMB(), the core stalls the doorbell store until the payload stores have been pushed out in order. The device then reads the frame just written.

Write FIFO payload __DMB Write doorbell Device reads payload

DMB versus DSB is the trade-off to state in an interview. DMB is enough for ordering, which is what the doorbell protocol needs. DSB adds completion: after it returns, the write is guaranteed visible to the device, so it suits a sequence where you immediately poll a status bit, disable a clock, or enter sleep and expect the device to have latched the command. Paying for DSB on every doorbell in a high-rate path wastes cycles for no ordering benefit.

The bench symptom is intermittent stale data that gets worse at higher clock speeds or with -O2, and disappears when you add a delay loop. That pattern points to store buffer timing rather than a logic error in the payload code. A GPIO toggled after __DSB() and probed beside the doorbell line confirms when the write actually completes.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-92A slave holds SCL low longer than your I2C master's stretch timeout: how do you configure the limit and recover the transfer?

The 90-second answer

Clock stretching is legal and unbounded in base I2C. A slave pulls SCL low after an ACK, or before sending a byte, to buy time. The master must wait with SCL released and not drive it high. If your master has a stretch timeout, that wait is capped. When the cap fires, you do not keep waiting and you do not just retry the same transfer. You abort with a STOP, clear the timeout flag, check whether SCL is still held low, and run bus recovery if it is. The timeout itself is set from the slave datasheet, not guessed: it must sit above the worst legitimate stretch and below the point where a hung slave blocks the bus for the whole system.

SMBus makes this explicit. The SMBus specification requires a timeout of 25 ms to 35 ms, because a slave that holds SCL low longer than that is treated as hung. Plain I2C has no timeout, so many MCU peripherals add one as a safety net, and many drivers implement it in software. STM32F7 and H7 I2C peripherals have a TIMEOUTR register for this. STM32F4 does not, so on F4 the driver has to bound the wait itself. The mechanism is the same either way.

Setting the limit

Find the largest stretch the slave can legally produce. That is usually in the datasheet as a conversion time, a write cycle time, or a maximum clock low time. Two common cases:

SlaveLegitimate stretchWhy
24C02 EEPROM, write cycle5 ms maxSlave holds SCL low while the internal write completes
Sensor in conversion10 ms to 30 ms, device specificSlave stretches while the ADC or heater settles
SMBus slave, any25 ms to 35 ms timeout requiredSpecification limit for a hung device

Set the master timeout above that figure with margin, and below your system budget. If the EEPROM needs 5 ms, a 10 ms timeout gives headroom without letting a dead slave stall a 100 ms control loop for long. If the sensor legitimately needs 30 ms, a 10 ms timeout will fire on every read and the driver will report a fault that is really a configuration error. That mismatch is the most common cause of intermittent I2C failures that only appear at temperature extremes, when conversion times grow.

On a part with TIMEOUTR, TIMEOUTA counts in units of 8 times the SCL period for the extended low period, so the count is the desired time divided by 8 times tSCL. At 100 kHz, tSCL is 10 us, so 8 times tSCL is 80 us, and a 10 ms limit needs 125 counts. Verify the field position and the enable bit in the reference manual for your exact family, they differ between F7 and H7, and confirm the result on a scope. On F4, implement the same bound in the polling loop with a free running timer:

C
/* 100 kHz SCL, 10 ms stretch limit, 1 MHz timer counter */
#define STRETCH_LIMIT_COUNTS 10000U  /* 10 ms at 1 MHz */

static int wait_scl_high(void)
{
    uint32_t start = TIM2->CNT;
    while (HAL_GPIO_ReadPin(I2C_SCL_GPIO_Port, I2C_SCL_Pin) == GPIO_PIN_RESET) {
        if ((uint32_t)(TIM2->CNT - start) > STRETCH_LIMIT_COUNTS) {
            return -1;  /* timeout, SCL still low */
        }
    }
    return 0;
}

The subtraction handles counter wrap. A logic analyser trace should show SCL held low for the expected stretch, then released, with no timeout path taken.

What happens when the timeout fires

The peripheral sets a timeout flag, or the software check returns, and the master stops waiting. At that point the bus state is unknown. The slave may still be holding SCL low, or it may have released it just after the timeout. The recovery sequence is:

C
if (wait_scl_high() != 0) {
    i2c_abort_and_stop();   /* STOP if possible, else peripheral reset */
    bus_recover();          /* 9 SCL pulses as GPIO, then STOP */
    i2c_reinit();
    return I2C_ERR_TIMEOUT;
}

Bus recovery means switching SCL and SDA to GPIO open drain, pulsing SCL up to 9 times while watching SDA, then issuing a STOP condition (SDA low to high while SCL high). Nine pulses clock out any byte the slave was trying to send. If SDA goes high during those pulses, the slave has released the bus. If SCL is still low after the pulses and you drive it high as GPIO, the slave is holding it. That is a hardware fault, not a software one. No amount of retry fixes a slave that never releases SCL. Log it, power cycle the slave if you have a load switch, and mark the device absent until the next probe.

A worked trace helps separate the cases. Assume 100 kHz, 10 ms timeout, EEPROM write cycle 5 ms.

TimeSCLSDAEvent
0 mshighstartMaster sends START, address, ACK received
0.2 mslowdataSlave ACKs first byte, then holds SCL low for write cycle
5.2 mshighdataSlave releases SCL, master continues
5.3 mshighstopTransfer completes, no timeout

Now the hung case. The slave holds SCL low past 10 ms. The timeout fires at 10 ms, the master aborts, and recovery runs. If the slave releases SCL during recovery, the next transfer succeeds. If it does not, the GPIO check shows SCL low even when the master drives it high, which points to a short, a latch-up, or a slave that needs a reset pulse on its reset pin.

Failure modes to name in the interview

Timeout set too short: every legitimate conversion fails, error rate rises with temperature, and the scope shows the slave releasing SCL just after the abort. Fix the timeout, not the slave.

Timeout set too long or disabled: a hung slave blocks the bus indefinitely, the watchdog fires, and the device resets in the field. This is why the timeout exists even though base I2C does not require it.

No STOP after timeout: the slave stays in a mid-byte state and interprets the next START as data. The next transfer gets a NACK or garbage. Always generate STOP or reset the peripheral before retrying.

Treating timeout as NACK: a NACK means the address or data was not accepted. A timeout means the slave accepted and then stalled. Retrying a NACK immediately is often fine. Retrying a timeout without recovery usually repeats the stall.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-93How do you validate a bootloader image's length, hash and metadata so a truncated image is rejected even if the signature check is bypassed?

The 90-second answer

Treat length, hash and metadata as independent gates, not as decorations on the signature. The bootloader parses the header inside strict slot bounds, recomputes the hash over exactly the bytes it will boot, and only then checks the signature. If the signature routine is skipped, patched out, or returns success by fault, a truncated image still fails the hash and length gates and never reaches the jump.

Assume a Cortex-M slot with a fixed header at the slot base, a declared image length, a stored hash, and a header CRC. The header is untrusted input. Nothing in it is used to size a read until it has been range checked against the slot size from the linker script, not against a value from the image itself.

C
/* Checked against Cortex-M33 / STM32H7 style slot layout. */
#define SLOT_BASE   0x08020000u
#define SLOT_SIZE   0x00040000u   /* 256 KiB */
#define RAM_BASE    0x20000000u
#define RAM_SIZE    0x00020000u

typedef struct __attribute__((packed)) {
    uint32_t magic;        /* 0x424C494D */
    uint16_t header_len;
    uint16_t flags;
    uint32_t image_len;    /* bytes after header */
    uint32_t entry_offset; /* offset of vector table from image start */
    uint32_t version;
    uint32_t anti_rollback;
    uint8_t  sha256[32];   /* over image_len bytes only */
    uint32_t header_crc;   /* CRC32 over all fields above */
} image_header_t;

bool validate_image(const image_header_t *h, uint8_t *computed_hash)
{
    if (h->magic != 0x424C494Du) return false;
    if (h->header_len < sizeof(image_header_t)) return false;
    if (h->header_len > SLOT_SIZE) return false;
    if (h->image_len == 0) return false;
    /* Subtraction form: no overflow in header_len + image_len. */
    if (h->image_len > SLOT_SIZE - h->header_len) return false;
    if (h->entry_offset >= h->image_len) return false;
    if (h->entry_offset & 3u) return false;
    if (h->anti_rollback < stored_anti_rollback()) return false;

    const uint8_t *image = (const uint8_t *)SLOT_BASE + h->header_len;
    sha256(image, h->image_len, computed_hash);
    if (memcmp(computed_hash, h->sha256, 32) != 0) return false;

    /* Vector sanity: initial SP in RAM, reset handler in flash, Thumb bit set. */
    uint32_t sp = *(const uint32_t *)(image + h->entry_offset);
    uint32_t pc = *(const uint32_t *)(image + h->entry_offset + 4);
    if (sp < RAM_BASE || sp > RAM_BASE + RAM_SIZE || (sp & 7u)) return false;
    if ((pc & 1u) == 0) return false;
    pc &= ~1u;
    if (pc < SLOT_BASE + h->header_len || pc >= SLOT_BASE + SLOT_SIZE) return false;
    return true;
}

The caller runs this, then the signature check over header plus hash, then sets VTOR, loads SP and jumps. A failure at any gate goes to the fallback slot or recovery mode. There is no path where a failed hash is logged and boot continues because the signature passed, and no path where a passed signature skips the hash.

no yes no yes no yes no yes Read header from slot base Magic, header_len and image_len in bounds? Reject, boot fallback Recompute SHA-256 over image_len bytes Hash matches header? Header CRC, version, anti-rollback, SP and PC sane? Verify signature over header and hash Set VTOR, load SP, jump
CaseWhat the check seesResult
Image truncated by 4 KiB, header intactimage_len still claims full size, hash over the short data differs, erased tail reads 0xFFReject on hash mismatch
image_len edited to the short sizeHash in header still covers the original length, recomputed hash differsReject on hash mismatch
image_len set to 0xFFFFF000 to wrap the end addressimage_len > SLOT_SIZE - header_lenReject on bounds, before any read
Header truncated, header_len claims 64 but slot data ends earlyHeader CRC fails, fields read as 0xFF fail magic and range checksReject on header CRC and bounds
Hash and length forged to match truncated codeHash passes, signature over header and hash failsReject on signature, which is why hash alone is not authentication

Two details catch candidates out in practice. First, the hash must cover the exact byte count that will execute, starting after the header, and the bootloader must not trust a separate "actual length" from a trailer or update protocol that the image can also rewrite. Second, metadata needs its own integrity. A header CRC catches torn writes and bit flips in the header itself, while the anti-rollback counter and version are checked before the hash, so a replayed older complete image does not boot just because its hash is valid.

The limit is honest: if an attacker can rewrite both the image and its stored hash and the signature check is truly bypassed, length and hash will not stop a deliberately forged image. They stop the common failure, a torn or truncated update that would otherwise jump into erased flash or a half written vector table. That is the point of layering them ahead of, and independently from, the signature.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-94Your sensor must respond within 1 ms of an event and runs on battery: how would you choose between Sleep and Stop modes on a Cortex-M MCU?

The 90-second answer

Assume a Cortex-M4 on a 3.3 V battery rail, and the sensor needs 300 µs to warm up after power returns. The 1 ms deadline covers wake, clock restart, sensor warm-up and the first read. I would compare Sleep and Stop 1 first, because both keep SRAM and resume without a reset. Standby loses SRAM and reboots, so it cannot meet 1 ms for this sensor.

Sleep is WFI with clocks still running. The core stops executing, but the clock tree, SRAM and peripherals keep their state. Wake is interrupt entry, typically 2 to 10 µs. Current is higher because clocks and regulators stay on, often 100 µA to 1 mA depending on what stays enabled.

Stop 1 gates the core and bus clocks and switches the regulator to low power. SRAM and register context are retained, so execution resumes after the wake handler. The cost is clock restart. The PLL and bus clocks must be restored before peripherals work again, so wake is typically 30 to 100 µs. Current drops to roughly 5 to 20 µA for the MCU alone.

ModeSRAM retainedWake latencyTypical MCU current*Meets 1 ms with 300 µs sensor warm-up?
Sleep (WFI)Yes2 to 10 µs100 µA to 1 mAYes
Stop 1Yes30 to 100 µs5 to 20 µAYes
StandbyNo, except backup registersReset and boot, milliseconds1 to 3 µANo

*MCU only, 25 °C, sensor and regulator excluded. Check the exact part, leakage rises with temperature.

Work the Stop 1 budget with real figures. Wake and clock restore: 100 µs. Sensor warm-up: 300 µs. Sensor read over I2C at 400 kHz: about 120 µs. Total is about 520 µs, inside 1 ms with margin for interrupt entry and processing. Sleep gives about 420 µs for the same job. Both fit, so the choice comes down to energy between events.

If events arrive every 10 s and the active load draws 12 mA for 50 ms, average active current is 60 µA. Sleep at 200 µA between events would dominate the battery budget. Stop 1 at 10 µA adds little, so Stop 1 wins despite waking slower. If events arrive every 100 ms, Stop 1 pays its wake cost ten times more often, and Sleep can win on total energy. That frequency is the deciding figure, not the sleep current alone.

C
/* Cortex-M, bare metal */
static void enter_sleep(void)
{
    __WFI(); /* Clocks keep running, wake is just interrupt entry. */
}

static void enter_stop1(void)
{
    HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);
    SystemClock_Config(); /* Must run again before using PLL or bus clocks. */
    sensor_power_on();
    start_warmup_timer_us(300);
}

Two checks before committing. First, confirm the wake pin is a valid wake source in Stop. On many STM32 parts only specific EXTI lines and the RTC wake from Stop, so a pin that works in Sleep may not work in Stop. Second, measure wake latency with a scope on a GPIO, not with the debugger attached. A debugger keeps clocks and flash acceleration alive and makes Stop look faster than it is in the field.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-95Why does a fault often disappear when you run firmware under a debugger?

The 90-second answer

A debugger changes timing. It halts the core, slows execution, and often runs a different build. A fault that needs two events to land within a few microseconds can stop happening when the gap between them grows to milliseconds. The code did not get fixed. The conditions that triggered it got removed.

Timing is the main effect

Most disappearing faults are races. An interrupt, a DMA completion, or a peripheral flag arrives while main code is halfway through a shared update. Under a debugger, breakpoints, single stepping, and register reads insert pauses of 1 ms or more. The event that would have landed in the middle of the update now lands before or after it. The bad interleaving never occurs.

Halting also changes the relationship between the core and the hardware. On many STM32 parts, debug freeze bits decide whether timers keep running while the core is halted. Either setting changes relative timing. A watchdog, SysTick, or sensor data ready line that was marginal at full speed can look fine once the core stops repeatedly.

C
volatile uint32_t rx_count;

void UART_IRQHandler(void)
{
    rx_count++;
}

void process(void)
{
    uint32_t seen = rx_count;
    if (seen != last_seen) {
        handle_frame(seen);
        last_seen = seen;
    }
}

At 168 MHz the ISR can fire between the read of rx_count and the update of last_seen. Single stepping stretches that gap so far that the UART byte arrives long after process() returns. The race is hidden, not solved.

Optimization changes the code itself

Debug builds usually use -O0. Release builds use -O2 or -Os. The compiler then inlines functions, caches values in registers, and reorders operations. A missing volatile on a memory mapped register can pass at -O0, where the compiler reloads the register each iteration, and hang at -O2, where it hoists the load out of the loop. Signed overflow has the same pattern. At -O0 it often appears to work by accident. At -O2 the compiler may assume it never happens.

Debug build under probeRelease build in the field
OptimizationUsually -O0, slow and literal-O2 or -Os, inlined and reordered
Core stateHalted often, interrupts disturbedFree running, interrupts land anywhere
Clocks and sleepProbe keeps debug clocks on, sleep often blockedNormal sleep and wake cycles
Image loadProbe flashes, resets, and starts from resetBootloader or internal flash starts the part

Probe loading changes startup and power state

A probe flash through SWD or JTAG resets the part and starts execution from the reset vector. A standalone boot may take a different path through a bootloader, with different clock setup and different initial RAM contents. The probe also powers the debug interface and can prevent deep sleep. A fault that needs a sleep and wake cycle, or a peripheral clock to stop, will not reproduce while the probe holds the part awake.

Fault in the field Attach debugger Core halts and slows down Race window changes Fault does not reproduce Code looks correct under debugger

How to reproduce it without the probe

Run the exact release image under the debugger, with the same optimization and linker script as the shipped build. A pass in a separate -O0 build is weak evidence. For observation without halting, write events to a RAM ring buffer and dump it later, or toggle a GPIO at the suspect point and measure it with a logic analyzer. If adding a small delay in free running code makes the fault vanish, you have found a timing window. Fix the synchronization that created the window, not the delay.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-96How would you select an MCU for a battery-powered sensor that must run for five years, wake every 10 seconds, and keep its configuration in sleep?

The 90-second answer

I would start from the energy budget, not the core. For a five year product on a CR2450 (620 mAh nominal, assume 500 mAh usable after derating and self discharge), the average current ceiling is 500 mAh / 43,800 h = 11.4 uA. Everything else, sleep current, wake energy, memory retention and peripherals, has to fit under that number with margin for cold temperature and battery ageing.

Then I would list the non negotiables: wake source and latency, what state must survive sleep, which peripherals must run in sleep (RTC, low power timer, UART, I2C, ADC, radio), and the peak current the battery and regulator can supply. Only after that would I compare MCUs. A part with 0.8 uA sleep current but a 3 ms wake, no SRAM retention in its deepest mode, and a 200 uA regulator quiescent current will lose to a part with 2 uA sleep current that wakes in 50 us, keeps SRAM, and runs its radio from a low Iq regulator.

Worked budget, hypothetical but realistic figures

Assume a sensor wakes every 10 s, runs for 40 ms at 8 mA (MCU, sensor, regulator losses included), then sleeps at 2 uA.

TermCalculationAverage current
Sleep2 uA continuous2.0 uA
Active8 mA x 0.040 s / 10 s32.0 uA
Total2 + 3234.0 uA
Life on 500 mAh usable500 / 0.03414,700 h, about 1.7 years

That fails the five year target before any radio transmission. The fix is not a lower sleep current. It is a shorter or lower current active window, a longer interval, or a bigger battery. If the active window drops to 12 ms at 5 mA, the active term becomes 6 uA, total 8 uA, life about 7 years. This is why wake energy matters more than the headline sleep number in most duty cycled products. Wake energy includes regulator ramp, crystal or RC startup, flash wake, sensor warm up and any calibration the firmware does on every wake. A sensor that needs 20 ms to warm up dominates the budget even if the MCU wakes in 50 us.

Comparison that decides it

CriterionDeep sleep with SRAM retentionDeep sleep without retentionShallow sleep, peripherals on
Typical current at 3.3 V, 25 C1 to 3 uA0.5 to 1 uA10 to 50 uA
Wake time50 us to 2 ms2 to 10 ms, reload from flashUnder 10 us
SRAM and registersRetained, sometimes only SRAM2Lost, restore from flash or backup registersRetained
RTC, low power timer, wake on UART or I2CUsually yesRTC often yes, others noYes
CostSlower wake, sometimes higher sleep currentLowest sleep current, boot code on every wakeHighest sleep current

On STM32L4 parts, for example, STOP2 retains SRAM and registers with wake in tens of microseconds, while STANDB loses SRAM and wakes through reset. On nRF52 parts, System OFF loses RAM, System ON keeps it but costs more current. The datasheet table alone does not tell you which mode your firmware can actually use. Check the retention column, the wake source list for that mode, and whether the ADC, I2C or radio clock domain is alive in that mode.

Memory trade off follows the same logic. If you need 32 KiB of retained RAM for a radio stack or a log buffer, you may be forced into a higher current sleep mode or a larger die. If configuration fits in backup registers or a small retained SRAM block, you can use the deeper mode and reload the rest from flash. Flash size also interacts with wake. Code that runs from flash in sleep wake paths, or code copied to RAM on wake, adds time and energy on every cycle.

How I would verify it

I would measure, not trust the headline number. Sleep current on a datasheet is usually measured at 25 C, with no GPIOs connected, no pull ups, and a lab supply. On a real board, GPIO leakage through a sensor, a 10 k pull up, and regulator quiescent current can add 5 to 20 uA. I would put the board on a current profiler, log current against a GPIO toggled at sleep entry and wake exit, and integrate charge per wake cycle.

C
/* Cortex-M, enter the retained sleep mode, wake on RTC */
__DSB();
__ISB();
HAL_PWR_EnableWakeUpPin(PWR_WAKEUP_PIN1); /* RTC alarm */
HAL_PWR_EnterSTOPMode(PWR_REGULATOR_VOLTAGE_SCALE1,
                      PWR_STOPENTRY_WFI);
/* On wake: restore clocks, check wake flag, then run sensor */

Failure modes I have seen: the regulator Iq exceeds the MCU sleep current by a factor of ten, the crystal startup is skipped in the chosen mode so the UART baud rate is wrong after wake, and the sensor needs a power rail that is off in sleep, so its warm up time was never counted. Each one shows up only in the integrated charge per cycle, not in a sleep current reading taken with a multimeter.

My selection order is therefore: energy budget with measured wake charge, sleep mode that retains what I need and wakes on the right source, peripherals that run in that mode, memory that fits the retention plan, and only then core performance and price. If two parts pass, I pick the one whose sleep mode I can measure and reproduce across temperature, not the one with the smaller number in the first column of the datasheet.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-97Your product line ships rev A and rev B boards with different sensors and pin mappings: how would you structure the firmware so one codebase supports both without forking the application?

The 90-second answer

Keep one application and one HAL, and push every difference between rev A and rev B into a board layer that is selected at runtime, not by recompiling. The application calls hal_sensor_read(), hal_led_set() and hal_motor_pwm(). Those functions never touch a register or a pin number. They dispatch through a capability table for the board that was detected at boot. Adding rev C then means adding one table and one board implementation, not touching application code.

Detection has to happen before any peripheral that differs is initialised. On a Cortex-M that means in SystemInit or the first lines of main, before clocks for the affected peripherals are enabled. I would not use a compile-time #ifdef REV_B scattered through drivers. That creates two untested binaries and makes a field update risky, because the wrong image can brick a board.

For detection, use hardware that cannot be changed by firmware. A resistor divider on an ADC input, a strapping pin pair, or a board ID EEPROM all work. An ADC divider is cheap and readable with the ADC you already have. Example: rev A fits 10 kΩ to 3.3 V with a 10 kΩ to ground, giving about 1.65 V. Rev B fits 47 kΩ to 3.3 V with a 10 kΩ to ground, giving about 0.58 V. With a 12-bit ADC and a 3.3 V reference those are counts near 2048 and 720. Set thresholds midway, for example below 1200 is rev B, above 1200 is rev A, and treat anything outside 400 to 2400 as unknown and enter a safe state instead of guessing.

C
typedef enum { BOARD_REV_A = 0, BOARD_REV_B = 1, BOARD_UNKNOWN = 2 } board_rev_t;

typedef struct {
    board_rev_t rev;
    uint8_t sensor_addr;      /* I2C address */
    uint8_t sensor_type;      /* 0 = old sensor, 1 = new sensor */
    uint16_t pwm_period;      /* timer ARR value */
    bool has_fan_tach;        /* rev B adds a tach input */
} board_caps_t;

static const board_caps_t caps_a = { BOARD_REV_A, 0x48, 0, 999, false };
static const board_caps_t caps_b = { BOARD_REV_B, 0x49, 1, 1999, true };

board_rev_t board_detect(void)
{
    uint16_t counts = adc_read_once(BOARD_ID_ADC_CH);
    if (counts > 400 && counts < 1200) return BOARD_REV_B;
    if (counts >= 1200 && counts < 2400) return BOARD_REV_A;
    return BOARD_UNKNOWN;
}

The HAL stays stable because its signature and units do not change when the hardware does. hal_sensor_read() always returns millidegrees Celsius, even if rev A uses a sensor that reports in 0.1 °C steps and rev B uses one that reports raw counts. The conversion lives in the board driver for that sensor. The same applies to pin mapping. The application asks for HAL_PIN_STATUS_LED, the board layer maps that to PA5 on rev A and PB1 on rev B, including the active level if it changed.

DifferenceRev ARev BHandled in
Sensor I2C address0x480x49capability table
Sensor register layout16-bit result12-bit result, left alignedsensor driver selected by sensor_type
PWM period for same frequencyARR 999 at 48 MHzARR 1999 at 96 MHzcapability table, timer init
Fan tach inputabsentpresent on PB6capability flag, application checks before reading
Status LED pin and polarityPA5, active highPB1, active lowboard pin map
Application Stable HAL Board capability table Board rev A driver Board rev B driver Registers and pins

Boot order matters. Read the board ID, validate it, store a pointer to the capability table in a const global, then initialise clocks, GPIO and peripherals from that table. If detection returns unknown, do not initialise the sensor or motor. Blink a known-safe LED pattern if one exists, log the raw ADC count over the debug UART, and stop. Guessing a revision and driving a 96 MHz timer setup on a 48 MHz board, or probing the wrong I2C address, wastes time and can damage a load.

Two failure modes come up in review. First, detecting the revision after the HAL has already cached pin numbers or timer settings. The fix is a single detection point and a rule that no HAL function runs before it, enforced by an assert in debug builds. Second, letting the application branch on if (rev == REV_B) in a dozen places. That leaks board knowledge upward and the branches drift. The application should branch on capabilities, such as if (caps->has_fan_tach), so a future rev C with the same tach input reuses the code.

For updates, put the supported board mask in the image metadata and have the bootloader check it against the detected revision before booting. That stops a rev B image being flashed to a rev A unit during a service visit. Test both revisions in CI with the capability table swapped, and keep a host unit test that feeds the detector the ADC counts for each resistor value plus the out-of-range cases. On the bench, measure the divider voltage with a meter before trusting the ADC thresholds, because a 1% resistor tolerance and ADC offset move those counts by tens of counts, not hundreds, and the gap between 720 and 2048 leaves room for that error.

Curated: · Written: · Reviewed: —

Difficulty: Medium