Skip to content
Tech Interview Prep
Technical interview guide

Communication Protocols: SPI, I2C, UART

The three workhorse serial buses for talking to peripherals and other boards: how each is wired and clocked, and when to reach for which.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: NXP UM10204 revision 7; CMSIS-Driver 6 SPI/I2C/USART interfaces; current Zephyr peripheral APIs reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

How do UART, I2C, and SPI compare across wire count, throughput, clock synchronization, bus topology, and hardware complexity?

Answer

Pick by clocking model first: it decides everything else. UART has no clock line, so both ends must agree on a baud rate and re-synchronise on every start bit; that makes it point-to-point, cheap, and drift-limited. I2C and SPI both carry a clock, so they are synchronous and can share a bus: I2C spends two wires plus in-band addressing to get multi-drop, SPI spends wires to get speed and near-zero protocol logic. On a board the deciding axis is pin budget against required payload rate.

AxisUARTI2C (UM10204)SPI (no formal standard; typical MCU block)
Wires2 (TX, RX); 4 with RTS/CTS2 (SDA, SCL), open-drain, plus pull-ups4 for one slave (SCLK, MOSI, MISO, CS); 3 + N for N slaves with individual CS; 3 + 1 daisy-chained
ClockAsynchronous. Shared baud rate, re-synced on each start bit, 16× oversamplingSynchronous, SCL driven by master; slave may stretch SCL lowSynchronous, SCLK driven by master; continuous or gated per transfer
TopologyPoint-to-point full-duplex (RS-485 extends it to a half-duplex multidrop)Multi-master, multi-slave, 7- or 10-bit addressing, arbitration on collisionSingle master, multi-slave via CS; no addressing, no arbitration
Throughput115.2 kbaud typical; 1–3 Mbaud common on MCUs, ~12 Mbaud on dedicated bridges100 k / 400 k / 1 M / 3.4 Mbit/s (Standard / Fast / Fast+ / High Speed)10–50 MHz common; some MCUs clock past 100 MHz
ComplexityNo clock line, but the baud divisor must land inside toleranceSTART/STOP, ACK/NACK, addressing, arbitration, clock stretchingShift register in silicon; cost is pins and the absence of any ACK

What the wire actually carries. Protocol overhead is not a rounding error at these rates:

LinkClocks or bit-times per byteEffective payload
UART 115.2 kbaud, 8N110 (1 start + 8 data + 1 stop)11.5 kB/s
UART 3 Mbaud, 8N110300 kB/s
I2C Fast 400 kHz9 (8 data + ACK)44.4 kB/s
I2C High Speed 3.4 MHz9, plus the HS master-code byte~370 kB/s
SPI 50 MHz86.25 MB/s, each direction simultaneously

So SPI at 50 MHz is roughly 140× I2C Fast mode, and the gap is structural: I2C pays an ACK clock per byte and an open-drain edge that cannot be driven fast.

Two numbers that decide real designs.

Baud divisor. A 16 MHz system clock divided by 16 × 115200 gives 8.68, so the nearest integer divisor is 9 and the actual rate is 16e6/(16×9) = 111.1 kbaud: 3.6% low. The 8N1 frame is 10 bit-times and the stop bit is sampled at 9.5 bit-times, so the total error budget is 0.5/9.5 ≈ 5.3%, i.e. ±2.6% per side. 3.6% on one side blows it. Switching to 8× oversampling gives 16e6/(8×115200) = 17.36 → divisor 17 → 117.6 kbaud, +2.1%, which fits. This is why 14.7456 MHz exists: 14.7456e6/(16×115200) = 8 exactly.

I2C pull-ups. Fast mode needs t_r ≤ 300 ns, and t_r = 0.8473 × Rp × Cb. The sink must also reach VOL = 0.4 V at IOL = 3 mA, so Rp(min) = (3.3 − 0.4)/3 mA = 967 Ω. At Cb = 400 pF, Rp(max) = 300 ns/(0.8473 × 400 pF) = 885 Ω: below Rp(min), so no valid resistor exists. The two limits cross at Cb ≈ 366 pF. At 3.3 V, keep a Fast-mode bus under ~350 pF, not the 400 pF the spec table lists.

Failure modes and how you see them.

  • I2C bus lockup. A slave reset mid-byte holds SDA low; the master's own reset does not clear it. Detect: SDA reads low while SCL is idle high. Recover by clocking SCL nine times manually, then issuing STOP.
  • I2C arbitration loss / NACK. The ARLO and NACK status bits fire; a NACK on address means the device is absent or its address strapping is wrong.
  • SPI silent failure. There is no ACK. A dead or unpowered slave just returns 0x00 or 0xFF on MISO. Detect by reading a known device ID register (JEDEC ID on flash) at init, and by checking CPOL/CPHA against a known pattern: a mode mismatch shifts every byte by one bit and looks like plausible data.
  • UART framing and overrun. The framing-error flag means the stop bit was not high (baud mismatch or noise); the overrun flag means the RX buffer was not read in time. Both are status-register bits, not exceptions.

When not to use each. SPI has no error detection, no flow control and no addressing: do not run it over a metre of cable; use RS-485 or CAN. I2C is not a bulk-data bus: 9 clocks per byte and open-drain edges cap it well below SPI. UART without a transceiver is point-to-point only, and without RTS/CTS it will overrun under sustained load.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

How do CPOL and CPHA define the four SPI clock modes, and what happens at the physical pin level during data sampling and shifting across them?

Answer

CPOL sets the idle level of SCK; CPHA sets which edge samples. The four modes are just those two bits. The mode is not a free choice: the peripheral's datasheet dictates it. If the datasheet lists multiple modes, Mode 0 is the default because it is the most widely supported and the reset default of most MCU SPI peripherals.

ModeCPOLCPHASCK idleSample edgeShift edge
000LowRising (leading)Falling (trailing)
101LowFalling (trailing)Rising (leading)
210HighFalling (leading)Rising (trailing)
311HighRising (trailing)Falling (leading)

At the pin level, every transfer alternates between two actions: the transmitter changes the level on MOSI (or MISO), and the receiver latches the level. These must happen on different edges, otherwise the receiver would sample a value that is changing. CPHA decides which edge does which. With CPHA=0, the leading edge samples and the trailing edge shifts. The first bit must therefore be valid on MOSI before the first leading edge: the master drives it when /CS asserts. With CPHA=1, the leading edge shifts and the trailing edge samples. The first leading edge launches the first bit, and the slave has until the trailing edge to see it.

Mode 0 vs Mode 3 (both sample on rising, differ in idle level):

Mode 0 (CPOL=0, CPHA=0):
/CS  : --\______________________________________/--
SCK  : ______/‾‾\__/‾‾\__/‾‾\__/‾‾\_______________
MOSI : --< b7 >< b6 >< b5 >< b4 >-----------------
Sample:      ^      ^      ^      ^
          (Rising edge 1, 2, 3, 4)

Mode 3 (CPOL=1, CPHA=1):
/CS  : --\______________________________________/--
SCK  : ‾‾‾‾‾‾\__/‾‾\__/‾‾\__/‾‾\__/‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
MOSI : -------< b7 >< b6 >< b5 >< b4 >------------
Sample:          ^      ^      ^      ^
              (Rising edge 1, 2, 3, 4)

Deciding criteria:

  • Datasheet wins. If it says Mode 3, use Mode 3. If it says Mode 0 or Mode 3, pick Mode 0.
  • Mode 0 vs Mode 3: both sample on the rising edge. Mode 3 idles high. Devices that sample on the rising edge often accept either because they ignore the first falling edge. Mode 0 is the default because it is the most common and the MCU peripheral default.
  • CPHA=0 vs CPHA=1: CPHA=0 lets you stretch the setup time for the first bit by delaying the first clock edge after /CS. CPHA=1 gives a fixed half-period setup for the first bit but does not require the master to pre-drive MOSI. CPHA=1 is used by devices that need the clock edge to launch their data.
  • Multiple slaves with different modes: reconfigure the master between transactions. This is safe only when no /CS is asserted; changing CPOL while a slave is selected can generate a spurious edge. If reconfiguration is too slow, use separate buses.
  • Mode 1 and Mode 2 are rare because they sample on the falling edge.

Failure modes:

  1. Off-by-one bit shift (CPHA mismatch): a Mode 0 master talking to a Mode 1 slave samples on the first rising edge before the slave has shifted out its first bit. Every byte arrives shifted by one bit.
  2. Spurious clock edge (CPOL mismatch): if the master idles SCK low but the slave expects it high, the slave may see a falling edge when the master drives SCK low, count it as a clock, and start the frame one bit early.
  3. Early /CS de-assertion: in CPHA=0 the final sample is on edge 2N-1; in CPHA=1 it is on edge 2N. Driving /CS high after the leading edge of the last bit cuts off the transfer before the receiver latches the final bit.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Design and validate a serial-link strategy for SPI full duplex.

Answer

Assume a master with a standard SPI peripheral, 8-bit data, mode 0 (CPOL=0, CPHA=0), and a slave that follows a command-response protocol: it needs two dummy bytes after a command before it drives valid data. The strategy is to transmit a fixed dummy byte (0xFF) on every read to generate clocks, discard the command echo plus the two dummy bytes (three bytes total), then read the response. Move data with DMA into a 16-byte FIFO. Validate by checking the overrun flag, verifying byte alignment against a known pattern, and testing at the target clock rate.

SPI is full duplex: every clock shifts one bit out on MOSI and one bit in on MISO. A slave cannot send data unless the master provides clocks, so a read always costs transmitted bytes. The dummy value matters: if the slave decodes MOSI as commands, 0xFF must be a no-op; otherwise use 0x00 or a dedicated NOP command. The response offset is the number of dummy bytes the slave needs before it drives valid data: here, two. The discard count must match: discard the command echo plus the offset. Discard one byte too few and every subsequent read is shifted by one byte; discard one too many and you lose the first real byte.

Overrun happens when the RX FIFO fills before DMA or the CPU reads it. At 10 MHz, a byte arrives every 0.8 µs, so a 16-byte FIFO fills in 12.8 µs. If DMA latency exceeds that, the overrun flag sets and new data is dropped. Detect it by polling the overrun status bit after each transfer; clear it by draining the receive data register and reading the status register in the order the reference manual specifies: the order is not interchangeable. Missing dummy clocks look different: the slave never responds, so MISO stays at 0x00 or 0xFF. Add a timeout of, say, 100 µs and retry the command.

Alternatives: half-duplex (separate read and write phases) avoids dummy bytes for reads but loses simultaneous write. If the slave supports it, half-duplex is simpler and faster for read-only traffic. Hardware flow control, if the slave has a ready pin, removes the need for a fixed offset but adds a wire. Deciding criteria: use full duplex when you must write and read in the same transaction, or when the slave only supports full duplex; use half-duplex when reads dominate and the slave allows it.

Worked trace: read two bytes from a slave that returns 0xAA, 0x55 after two dummy bytes.

clockMOSIMISOaction
10x010x00command, discard
20xFF0x00dummy 1, discard
30xFF0x00dummy 2, discard
40xFF0xAAfirst data byte
50xFF0x55second data byte

The slave drives 0xAA on clock 4, the first clock after the two dummy bytes. The discard count is three: command echo, dummy 1, dummy 2. The two data bytes are 0xAA and 0x55.

Validation checks:

Run these at the target clock rate (10 MHz) and at the maximum slave rate. Use a logic analyzer to confirm the slave drives MISO only after the expected number of clocks. If the slave has a FIFO, test with back-to-back reads to force overrun.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Design and validate a serial-link strategy for SPI chip select.

Answer

Core answer (first 90 seconds)

Assume a single master, active-low CS, and a SPI NOR flash (W25Q128JV) on a 50 MHz bus. The strategy: one CS assertion per logical transaction, with controller-managed setup and hold where the hardware provides it, and explicit delays where it does not. Never let the driver or DMA split a transaction across a CS deassertion.

Concretely: assert CS, wait tSLCH (5 ns min for the W25Q128JV), clock every byte of command and data without deasserting, wait tCHSH (5 ns min), deassert CS, then wait tSHSL (30 ns min) before the next transaction. On Linux, that means cs_change = 0 on all but the last transfer in a SPI_IOC_MESSAGE call, and cs_setup/cs_hold in struct spi_device if the controller supports it. On STM32H7, set SPI_CFG2.MSSI and SPI_CFG2.MIDI to insert the same gaps in hardware.

C
struct spi_ioc_transfer xfer[2] = {
    { .tx_buf = (unsigned long)&cmd, .len = 1, .speed_hz = 50000000,
      .cs_change = 0 },   /* keep CS low into the data phase */
    { .rx_buf = (unsigned long)buf, .len = 256, .speed_hz = 50000000,
      .cs_change = 1 },   /* deassert CS after the last byte */
};
ioctl(fd, SPI_IOC_MESSAGE(2), xfer);

Why it works

The device samples CS relative to SCLK. If CS changes within tSLCH of the first edge, the first bit is undefined; if it changes within tCHSH of the last edge, the last bit is undefined. For flash, CS high between command and data resets the command state machine, so a split transaction reads 0xFF. For devices with a commit model (some ADCs, flash page program), CS high is the trigger, so deasserting early aborts the operation.

Trade-offs

| CS source | Timing control | Devices | Determinism | Use when | | Controller hardware CS | Register fields (STM32 SPI_CFG2 MSSI/MIDI; Linux cs_setup/cs_hold) | 2–4 | ns, no jitter | SCLK > 10 MHz, tight tSLCH/tCHSH | | GPIO CS | Linux cs_gpiod + cs_setup/cs_hold; otherwise software delay | Many | µs jitter from scheduling | Many devices, loose timing | | I2C/SPI expander CS | Software, plus I2C latency | Very many | Worst jitter | Slow buses, non-critical |

Pick hardware CS when the device minimum is under ~10 ns or the transaction must not be split. Pick GPIO CS when you need more devices than the controller has CS lines, and accept that you must add delays and validate them.

Failure modes and detection

| Failure | Mechanism | Detection | Cost | | CS deasserted mid-transaction | Driver splits transfer or cs_change=1 on wrong transfer | Scope CS vs SCLK; read returns 0xFF | Silent corruption | | Two CS asserted | GPIO expander race or shared CS | Supply current spike; MISO contention | Driver damage | | GPIO CS skew | CS over I2C expander, asserts after SCLK | Measure CS-to-SCLK skew > tSLCH | First bit lost | | DMA ends before last clock | CS deasserts early | Scope CS vs last SCLK; CRC/length mismatch | Truncated byte | | Deselect aborts commit | CS high before last data byte | Read status WIP bit; never sets | Lost write |

Validation

Static: dump the device tree, confirm spi-cs-setup-delay-ns and spi-cs-hold-delay-ns (or the controller register values) meet the device minimum. Dynamic: scope CS, SCLK, MOSI, MISO at max clock and max temperature; measure tSLCH, tCHSH, tSHSL. Stress: 10^6 read-ID cycles with concurrent DMA and IRQ load; count mismatches. Fault injection: add 1 µs to the GPIO CS path and confirm the driver reports a CRC or timeout rather than returning stale data.

Worked trace

With cs_change = 0 on the command transfer and cs_change = 1 on the data transfer, a 50 MHz read of 256 bytes shows CS low from the first command bit through the last data bit, tSLCH = 12 ns, tCHSH = 8 ns, both above the 5 ns minimum. Setting cs_change = 1 on the command transfer instead makes CS high for 1.2 µs between command and data; the flash treats that as a new transaction and returns 0xFF for all 256 bytes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Compare dedicated Chip Select (CS) multi-slave SPI topology versus daisy-chain SPI topology in terms of hardware pins, software overhead, and throughput.

Answer

In a dedicated Chip Select (parallel) topology, all peripherals share SCLK, MOSI, and MISO lines, but each peripheral has an independent CS line routed directly from the SPI master (or GPIO controller). In a daisy-chain topology, SCLK and a single shared CS line are routed to all peripherals in parallel, but the data lines form a shift-register pipeline: the controller's MOSI connects to device 1's SDI, device 1's SDO connects to device 2's SDI, and the final device's SDO returns to the controller's MISO.

1. Hardware Pin Budget

  • Dedicated CS: Requires $3 + N$ controller pins for $N$ slaves (SCLK, MOSI, MISO, plus $N$ chip-select pins). If pin counts exceed microcontroller GPIO capacity, an external hardware demultiplexer (such as a 3-to-8 decoder like 74HC138) can reduce master pins to $3 + \lceil\log_2 N\rceil$, at the cost of PCB routing complexity and component count.
  • Daisy-Chain: Requires exactly 4 controller pins ($3 + 1$) regardless of $N$ (SCLK, MOSI, MISO, and one common CS). However, every slave peripheral must silicon-support daisy chaining: internal registers must behave as transparent pass-through shift registers that propagate data on SDO while CS remains asserted, latching the shifted contents only on CS deassertion.

2. Software Overhead and Driver Complexity

  • Dedicated CS: Low software complexity per transaction. The master configures peripheral-specific clock polarity/phase (CPOL/CPHA), asserts a single CS pin, transmits $K$ bytes for that target device via DMA or FIFO, and deasserts CS. Unaddressed peripherals keep their SDO/MISO output drivers tri-stated (high impedance).
  • Daisy-Chain: Substantial framing overhead. To update even a single peripheral's 16-bit register in an $N$-device chain, the driver must synthesize a contiguous packet containing commands/data for all $N$ devices (a buffer of $N \times 16$ bits). If only device $K$ is targeted, the remaining $N-1$ positions must be loaded with vendor-specific NOP instructions. Furthermore, all devices must share identical SPI clock modes (CPOL/CPHA) and bit order.

3. Throughput and Latency

Let $N = 8$ devices, each processing 2 bytes (16 bits) per cycle over a 10 MHz SPI clock ($t_{\text{bit}} = 100\text{ ns}$):

MetricDedicated CS (Single 16-bit Target)Daisy-Chain ($N=8$ 16-bit Slaves)
Clock cycles per target update16 clocks128 clocks ($8 \times 16$)
Bus transmission time$1.6,\mu\text{s}$$12.8,\mu\text{s}$
Per-slave transaction latencyLow: immediate access to slave $K$High: must flush the entire pipeline
Simultaneous updateNo: requires $N$ sequential CS togglesYes: all latches trigger synchronously on CS rising edge

Failure Modes and Diagnostics

  1. Pipeline break / Bit corruption: In daisy chaining, a broken trace or single-bit framing error on device $k$'s SDO corrupts all subsequent downstream devices ($k+1 \dots N$). A logic analyzer must monitor inter-chip SDI/SDO nodes simultaneously to isolate which device dropped or inserted bits.
  2. MISO Contention in Dedicated CS: If a slave peripheral fails to enter high-Z on CS deassertion (e.g., due to slow tri-state disable timing $t_{\text{DIS}}$ or firmware race asserting two CS pins), bus contention corrupts reads from subsequent devices.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

How do you share one SPI bus among slaves that need different CPOL/CPHA modes and different maximum clock rates, and what are the trade-offs between reconfiguring the bus per transaction, grouping slaves by mode and speed, and giving a device its own bus?

Answer

SPI has no addressing and no per-slave configuration. SCLK, MOSI and MISO are shared, and CPOL/CPHA and the clock prescaler are properties of the master's peripheral, not of the slave. So when two slaves need different modes or different maximum rates, the master has to change its own configuration between their transactions. There are three ways to live with that, and the choice is driven by how short the transactions are and whether two devices must be serviced concurrently.

The ordering rule is not optional: deassert every CS, change CPOL/CPHA and the prescaler, then assert the target CS. Changing CPOL while a slave's CS is low puts a spurious edge on SCLK, and a stateful slave (a shift register, a flash in command mode) will count it as a bit. On controllers that require the peripheral disabled (SPE=0) to change mode or baud, the switch also flushes the TX/RX FIFO, so you cannot pipeline it behind the previous transfer.

strategycostwins when
Reconfigure per transactionRegister writes plus a bus idle gap per switch; FIFO flush on some controllersFew slaves, short transactions, latency-tolerant; at most two distinct modes on the bus
Group by mode + rateScheduling: batch transactions per group, hold a bus mutex, a device in the wrong group waitsMany slaves but few distinct modes; steady-state polling loops
Dedicated bus per device3 pins and one SPI peripheral instance per bus, plus PCB areaRate gap of roughly 4x or more, or two devices that must stream concurrently

Reconfiguration is cheap in absolute terms and expensive in relative terms. At 20 MHz a 4-byte transfer is 32 bits / 20 MHz = 1.6 us. A mode switch costing ~2 us of register writes plus a 1 us idle gap is ~190% overhead on that transaction. The same 4 bytes at 1 MHz take 32 us, so the switch is ~9%. That is why grouping wins for a bus of many short, frequent transactions and per-transaction reconfiguration is fine for a handful of long ones.

Zephyr makes the per-transaction strategy the default: the config is passed per call and applied around it, with CS deasserted between calls, which is exactly the ordering you want.

c /* Zephyr SPI: config applied per call, CS deasserted between calls. / static const struct spi_config adc_cfg = { .frequency = 20000000, .operation = SPI_OP_MODE_MASTER | SPI_WORD_SET(8) | SPI_TRANSFER_MSB | SPI_MODE_CPOL | SPI_MODE_CPHA, / mode 3 / }; static const struct spi_config eeprom_cfg = { .frequency = 1000000, .operation = SPI_OP_MODE_MASTER | SPI_WORD_SET(8) | SPI_TRANSFER_MSB, / mode 0 */ };

spi_transceive(adc_dev, &adc_cfg, &tx, &rx); /* 20 MHz, mode 3 / spi_transceive(eeprom_dev, &eeprom_cfg, &tx, &rx); / 1 MHz, mode 0 */

If you use SPI_HOLD_ON_CS to keep CS asserted across calls, you have taken the mode switch off the table for the duration of the hold: the hold and the reconfiguration are mutually exclusive.

Failure modes and how they show up:

  • Mode mismatch. Reads come back shifted one bit, or as 0xFF/0x00. Detect by reading a known ID register at the slowest prescaler before raising the rate.
  • Rate too high. Works cold, fails hot, because MISO setup time is violated. Detect with a logic analyzer measuring the MISO valid window against the sampling edge, then sweep the prescaler down until there is margin.
  • Reconfiguration glitch. A capture across the switch shows an SCLK edge while some CS is low.
  • Shared MISO contention. Two CS low at once; supply current rises and MISO sits mid-rail.
  • Missed bus mutex. Two tasks interleave and a transaction's bytes belong to two different devices.

When not to: if every slave happens to accept mode 0 at the slowest device's maximum rate, one config for the whole bus is simplest. Do not add grouping machinery for a bus that never needs it. And do not give a device its own bus just to dodge a mode switch; do it when the rate gap or the concurrency requirement forces it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design and validate a serial-link strategy for I2C electrical model.

Answer

Assumptions first. 3.3 V bus, standard-mode (100 kHz) or fast-mode (400 kHz), bus capacitance up to 200 pF, −40 to +85 °C. The deliverable is a pull-up window, a chosen value, and a measurement plan.

Core answer. I2C is open-drain: every device pulls the line low and releases it, and the pull-up resistor charges the bus capacitance back to VDD. Rise time is that RC, and the spec defines it between 0.3 VDD and 0.7 VDD: the same points as VIL and VIH. So pick Rp so the worst-case rise time meets the mode's tr limit, while keeping Rp large enough that a driver can still sink IOL at VOL ≤ 0.4 V.

  • Rp(max) = tr(max) / (0.8473 × Cb)
  • Rp(min) = (VDD − VOL(max)) / IOL(max)

The 0.8473 is the RC charge curve: t(0.3 VDD) = 0.3567 RC, t(0.7 VDD) = 1.2040 RC, difference 0.8473 RC.

Worked numbers. VDD = 3.3 V, Cb = 200 pF, VOL = 0.4 V, IOL = 3 mA (standard/fast mode).

modetr maxRp(max)Rp(min)chosenresulting tr
standard 100 kHz1000 ns5.9 kΩ967 Ω4.7 kΩ796 ns
fast 400 kHz300 ns1.77 kΩ967 Ω1.5 kΩ254 ns

Rp(min) = (3.3 − 0.4) / 3 mA = 967 Ω. So 4.7 kΩ is fine for standard mode; fast mode forces you below 1.77 kΩ, and 1.5 kΩ sits in the window. Fast-mode Plus (1 MHz, tr ≤ 120 ns, IOL = 20 mA) pushes Rp(max) to 708 Ω and Rp(min) to 145 Ω.

Trade-offs. Too large Rp: rise time exceeds tr, the line is still below 0.7 VDD when the receiver samples, and it degrades at high temperature (leakage) and high Cb. Too small Rp: the driver cannot hold VOL under 0.4 V, and you burn VDD/Rp continuously whenever the line is low. 1.5 kΩ at 3.3 V is 2.2 mA per low bit. Cb is the hard limit: 400 pF for standard/fast/HS, 550 pF for Fm+; tr scales linearly with it, so a connector or a long trace eats the margin.

Failure modes and how they show up.

  • Slow rise: scope shows tr over spec between 0.3 and 0.7 VDD; intermittent NACKs at max clock, worse hot.
  • VOL too high: measure at the driver pin with the line held low; a strong pull-up plus a weak sink gives a marginal low a receiver reads as high.
  • Level shifter: a discrete MOSFET pass-gate adds capacitance and a static offset; use a dedicated I2C translator (PCA9306-class) and re-check tr, since it adds both C and delay.
  • Unpowered device: its ESD diode to its own VDD rail clamps the bus, so the line never rises. Detect by removing power from one node and watching the high level; fix with a bus isolation switch or series resistor.

Validation. Compute the window, then measure at the corners: VDD min/max, −40/+85 °C, and Cb at max. Scope tr between 0.3 and 0.7 VDD, check VOL ≤ 0.4 V with the line low, and run the bus at max clock for bit errors. Temperature bites twice: hot raises driver on-resistance (VOL up) and leakage; cold sharpens edges but can ring.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

How do you calculate the minimum and maximum pull-up resistor values for an I2C bus based on supply voltage, bus capacitance, and rise-time requirements?

Answer

An I2C bus uses open-drain drivers with passive pull-up resistors ($R_p$). Sizing $R_p$ requires bounding it between two physical constraints: $R_{p(min)}$ to protect the driving FET and guarantee a valid low-level output voltage ($V_{OL}$), and $R_{p(max)}$ to meet the maximum bus rise time ($t_r$) against the total lumped bus capacitance ($C_b$).

1. Minimum Pull-Up Resistor ($R_{p(min)}$)

When an open-drain transistor pulls SDA or SCL low, it sinks current from $V_{DD}$ through $R_p$. The I2C specification specifies a maximum allowable low-level voltage $V_{OL}$ at a rated sink current $I_{OL}$. If $R_p$ is too small, current exceeds $I_{OL}$ and the voltage drop across the driver's internal $R_{on}$ raises $V_{OL}$ above the receiver threshold $V_{IL}$ (typically $0.3 \times V_{DD}$), preventing logic zero recognition.

From Ohm's law: $$R_{p(min)} = \frac{V_{DD} - V_{OL(max)}}{I_{OL}}$$

Per the UM10204 specification:

  • Standard-mode (100 kHz) and Fast-mode (400 kHz): $V_{OL} \le 0.4\text{ V}$ at $I_{OL} = 3\text{ mA}$.
  • Fast-mode Plus (1 MHz): $V_{OL} \le 0.4\text{ V}$ at $I_{OL} = 20\text{ mA}$.

2. Maximum Pull-Up Resistor ($R_{p(max)}$)

When devices release the bus, line capacitance $C_b$ charges toward $V_{DD}$ through $R_p$ following an RC exponential response: $v(t) = V_{DD}(1 - e^{-t / (R_p C_b)})$.

The I2C rise time $t_r$ is defined between $V_{IL(max)} = 0.3 \times V_{DD}$ and $V_{IH(min)} = 0.7 \times V_{DD}$:

  • Time to reach $0.3 \times V_{DD}$: $t_1 = -R_p C_b \ln(1 - 0.3) \approx 0.3566 \times R_p C_b$
  • Time to reach $0.7 \times V_{DD}$: $t_2 = -R_p C_b \ln(1 - 0.7) \approx 1.2040 \times R_p C_b$
  • Transition duration: $t_r = t_2 - t_1 = R_p C_b (\ln(0.7) - \ln(0.3)) = R_p C_b \ln(0.7 / 0.3) \approx 0.8473 \times R_p C_b$

Solving for $R_p$: $$R_{p(max)} = \frac{t_{r(max)}}{0.8473 \times C_b}$$

Specification limits for $t_{r(max)}$:

  • Standard-mode (100 kHz): $t_{r(max)} = 1000\text{ ns}$, bus capacitance limit $C_{b(max)} = 400\text{ pF}$.
  • Fast-mode (400 kHz): $t_{r(max)} = 300\text{ ns}$, bus capacitance limit $C_{b(max)} = 400\text{ pF}$.
  • Fast-mode Plus (1 MHz): $t_{r(max)} = 120\text{ ns}$, bus capacitance limit $C_{b(max)} = 550\text{ pF}$.

3. Worked Sizing Example

Consider Fast-mode (400 kHz) at $V_{DD} = 3.3\text{ V}$ with a measured/estimated bus capacitance $C_b = 150\text{ pF}$ (traces + pin capacitance of 5 slave devices at $\sim 10\text{ pF}$ each):

$$ R_{p(min)} = \frac{3.3\text{ V} - 0.4\text{ V}}{3\text{ mA}} = \frac{2.9\text{ V}}{0.003\text{ A}} \approx 966.7\ \Omega $$ $$ R_{p(max)} = \frac{300\text{ ns}}{0.8473 \times 150\text{ pF}} = \frac{300 \times 10^{-9}}{1.271 \times 10^{-10}} \approx 2360\ \Omega $$

Any standard resistor between $1\text{ k}\Omega$ and $2.2\text{ k}\Omega$ (such as $1.5\text{ k}\Omega$ or $2.0\text{ k}\Omega$) guarantees spec compliance. Selecting $1.5\text{ k}\Omega$ leaves headroom for temperature drift and trace aging while drawing only $1.93\text{ mA}$ during low phases.

Design Boundaries & Failure Modes

ConditionSizing ImplicationFailure Mode Observed
$R_p < R_{p(min)}$Pull-up too stiff$V_{OL} > V_{IL(max)}$; slaves fail to ACK; excessive quiescent current
$R_p > R_{p(max)}$Pull-up too weakRounded rising edges; setup time violations; missed clock edges at high baud rates
High $C_b$ (> 400 pF)Window collapses ($R_{p(max)} < R_{p(min)}$)Requires reducing bus speed, bus buffer/accelerator (e.g. PCA9515), or switching to Fm+ drive

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Design and validate a serial-link strategy for I2C transaction.

Answer

What I'd say first

I'd clarify two things before designing anything: is this a single-controller bus or multi-controller, and does the target device's datasheet show a combined-format figure? I'll assume 7-bit addressing, Fast-mode 400 kHz, one controller, and a register-mapped device at 0x48 on Linux 6.x. Under those assumptions the strategy is: model every register read as one atomic controller transaction (write the pointer, repeated START, read) and validate it at three levels: the transfer descriptor, the wire, and fault injection.

Why repeated START, not STOP+START

A register read is two address phases. If you put a STOP between them you release the bus. Two things break. Another controller can win arbitration and interleave its own traffic. And some devices reset their register pointer on STOP, so the read returns register 0x00 instead of the one you wrote. A repeated START holds SDA and SCL and re-issues the address with R=1 without releasing the bus, so the pointer write and the read are one transaction.

C
/* Linux 6.x, i2c_transfer */
struct i2c_msg msgs[2] = {
    { .addr = 0x48, .flags = 0,        .len = 1, .buf = &reg },  /* W: pointer */
    { .addr = 0x48, .flags = I2C_M_RD, .len = 2, .buf = val },   /* R: 2 bytes */
};
int n = i2c_transfer(adap, msgs, 2);
/* n == 2 on success; -ENXIO = address NAK; -EREMOTEIO = data NAK; -ETIMEDOUT = stretch/bus */

On the wire that is:

S 0x48+W A reg A Sr 0x48+R A d0 A d1 N P

S is START, Sr is repeated START, A is ACK, N is the controller's NACK on the last byte, P is STOP. The point of the check is that there is no P between the two address phases.

Trade-offs

Repeated START is atomic, but not every controller implements it in hardware; some need I2C_M_NOSTART to suppress the second START, and bit-banged i2c-gpio always can. STOP+START works on every controller but loses atomicity: only safe if the device latches its pointer across STOP and no other controller is present. SMBus block read (I2C_M_RECV_LEN) lets the device send a length byte first, which suits variable-length payloads, but the device must support it and the controller must support the flag. Moving to SPI removes addressing and arbitration entirely and is full duplex, at the cost of a chip select per device and more pins. The deciding criteria are: does the datasheet show a combined-format figure, does the controller support combined transfers, and is the bus multi-controller.

Failure modes and how I'd detect them

failuremechanismdetection
driver inserts STOPtransfer split into two i2c_transfer callslogic analyzer shows P between phases; pointer register readback mismatches
another controller intervenesbus released between phasescontroller reports arbitration lost; foreign address on the wire
device pointer changesauto-increment wrap or another writerread pointer register back before and after; two reads disagree
zero-length phaselen = 0 message rejectedi2c_transfer returns -EINVAL
wrong R/W bitI2C_M_RD missing-ENXIO (address NAK)
clock-stretch hangtarget holds SCL low-ETIMEDOUT; SMBus tTIMEOUT is 25–35 ms

Validation

Static: the descriptor must match the datasheet's combined-format figure, including the R/W bits. Wire: capture with a logic analyzer (sigrok/PulseView or Saleae) and assert Sr is present, no P sits between phases, and rise time stays inside the 400 pF bus-capacitance limit. Fault injection: force a STOP, add a second controller, and confirm the driver returns the right errno and retries or reports rather than silently returning stale data. Bus recovery: if a target holds SDA low, clock nine pulses then issue STOP.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Design and validate a serial-link strategy for I2C addressing.

Answer

Assume one master, 7-bit devices unless a 10-bit part is called out. The design: store canonical 7-bit addresses in one header, wrap them in a type that cannot be shifted by accident, and convert to the wire format only at the HAL boundary. Validate with a unit test that captures the first byte, a bus scan, and a logic-analyzer decode.

Design

C
// i2c_addr.h
typedef uint8_t i2c7_addr_t; // always 7-bit, 0x08..0x77
#define LM75_ADDR    ((i2c7_addr_t)0x48)
#define AT24C02_ADDR ((i2c7_addr_t)0x50)

_Static_assert(LM75_ADDR >= 0x08 && LM75_ADDR <= 0x77, "reserved I2C address");

// Linux i2c-dev: kernel shifts, pass 7-bit
int fd = open("/dev/i2c-1", O_RDWR);
ioctl(fd, I2C_SLAVE, LM75_ADDR); // 0x48 -> wire 0x90 write, 0x91 read
i2c_smbus_read_byte_data(fd, 0x00);

// STM32 HAL: expects 8-bit shifted
HAL_I2C_Master_Transmit(&hi2c1, LM75_ADDR << 1, buf, len, 100); // 0x90

// ESP-IDF: expects 7-bit
i2c_master_write_to_device(I2C_NUM_0, LM75_ADDR, buf, len, pdMS_TO_TICKS(100));

The wire byte is (addr << 1) | rw, where rw is 0 for write and 1 for read. The kernel, ESP-IDF and Zephyr take the 7-bit address and do that shift themselves. STM32 HAL and some NXP drivers take the already-shifted 8-bit value. Keep the shift in one adapter per platform, never at call sites.

Validation

  1. Compile-time: _Static_assert rejects 0x00-0x07 and 0x78-0x7F, the reserved 7-bit ranges.
  2. Unit test: mock the HAL, capture the first byte after START. For 0x48 write expect 0x90, read expect 0x91. For 0x50 write expect 0xA0. Run the table for every address in the header.
  3. Bus scan: i2cdetect -y 1 must show 0x48. If it shows 0x24, the shift is missing. If it shows 0x20, the address was shifted twice.
  4. Logic analyzer: decode the first byte as 7-bit address plus R/W. For LM75 write, expect 0x48 + W, which the analyzer may display as 0x90. Compare against the datasheet notation, not against the code constant.
  5. Integration: read a known register. BMP280 at 0x76 returns 0x58 from WHO_AM_I (0xD0). A wrong address usually returns NACK or a different device's ID.

Trade-offs

Storing 8-bit write addresses (0xA0 for AT24C02) matches some datasheets and STM32 HAL directly. But the read address is 0xA1, so you need two constants or compute one from the other, and a stray << 1 produces 0x40. Storing 7-bit is safer when the API takes 7-bit (Linux, ESP-IDF, Zephyr). The policy fails in a mixed codebase: if one file calls STM32 HAL and another calls Linux i2c-dev, a typed wrapper plus boundary adapters are mandatory. 10-bit devices need a separate type and an API flag such as I2C_M_TEN; never force them into i2c7_addr_t.

Failure modes

FailureMechanismDetectionCost
Double shift0xA0 << 1 = 0x40, device at 0x20 ACKsi2cdetect shows 0x20; unit test first bytehours chasing wrong sensor data
Missing shift0x48 passed to STM32 HAL sends 0x48, device at 0x24 ACKsi2cdetect shows 0x24; analyzersame
R/W embeddedAPI expects 8-bit with R/W, 7-bit passed -> read becomes writeread NACKs; analyzer shows R/W=0read path broken
Reserved address0x00-0x07 or 0x78-0x7F usedcompile-time assert; bus scan no ACKgeneral call to all devices
10-bit as 7-bitfirst byte 1111 0xx is reserved, no ACKNACK; analyzer shows 0xF0-0xF7device unreachable
Analyzer notation7-bit code vs 8-bit capturedecode both ways; compare to datasheetfalse debugging

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Design and validate a serial-link strategy for I2C acknowledgement.

Answer

What a strong candidate says first

Treat ACK and NACK as four separate signals, not one error bit, and give each its own decision rule. The bus is open-drain: on the ninth clock after every byte the receiver pulls SDA low to ACK, or leaves it high to NACK. Who the receiver is changes with the phase, and that is why the same bit means different things.

Decision rules

PhaseReceiver that drives the ACK bitNACK meansAction
Address, after START (7-bit address + R/W)TargetNo device at that address, or the device is busyRetry once after a bounded delay; if it persists, run a bus scan; if the device is busy, wait its write-cycle time
Data byte, writeTargetThe byte was rejected: write-protected region, unknown register, or full bufferDo not blind-retry. Read the status register if the device has one, and surface a semantic error
Data byte, read, not the lastMasterThe master wants to stop earlyAbort the read and issue STOP
Final read byteMasterNormal end of readNot an error. Never log it as a fault

The rule that catches most production bugs: a NACK is only an error when the target drove it. When the master drives it on the last read byte, it is the protocol working correctly.

Trace

Read two bytes from an LM75-class sensor at 0x48, pointer register 0x00, at 400 kHz:

START → 0x90 (0x48<<1 | write) → target ACK → 0x00 → target ACK → repeated START → 0x91 (read) → target ACK → byte MSB → master ACK → byte LSB → master NACK → STOP.

Five ACK bits, five ninth clocks. The first three are the target pulling SDA low. The fourth is the master pulling SDA low to say "send more". The fifth is the master leaving SDA high to say "stop": that NACK is the end-of-read signal, and a driver that flags it as a fault will log a false error on every successful read.

Trade-offs

The retry decision is the real design choice. Retrying helps with transient causes (arbitration loss in a multi-master bus, a clock-stretch timeout) because the transaction did not complete and retrying is safe. Retrying hurts when the target already committed the action: a "trigger conversion" or FIFO push that NACKs after committing will be duplicated. So key the retry policy on idempotency. Reads and register writes are idempotent; command triggers are not. For non-idempotent commands, verify by read-back or carry a sequence number instead of retrying. Linux's i2c core exposes a per-adapter retry count: set it deliberately rather than inheriting it.

Validation

Inject each case rather than trusting the happy path. Force a NACK by holding SDA high with a GPIO or jumper and confirm the driver classifies it by phase. Scan all 128 addresses and confirm only the expected devices ACK. Trigger an EEPROM write cycle, address the part immediately, and confirm it NACKs the address and then ACKs after its write-cycle time (5 ms max on an AT24C02). Write to a protected register and confirm the bus ACKs while the status register reports the reject: that is the semantic layer the bus cannot see. Capture the ninth clock on a scope or logic analyzer to confirm SDA state at the sampling edge.

Failure modes to detect

SDA stuck low when the bus is idle means a target died mid-byte; clock out nine pulses and issue STOP to recover. Clock stretching past the master's timeout needs a timeout longer than the slowest target's stretch, or the transaction fails spuriously. And a busy target that NACKs its address looks identical to an absent device: only the retry-then-ACK pattern distinguishes them.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design and validate a serial-link strategy for I2C clock stretching.

Answer

What I'd say first

Three things decide this design: the bus mode and speed, whether the controller samples SCL, and the worst-case stretch the slowest target legitimately needs. Clock stretching is a target holding SCL low after the controller has released it, so the controller must read SCL back and wait for it to actually go high before starting the next clock. A hardware block that drives SCL on a fixed schedule and never samples it will not stretch: it clocks straight through and corrupts the byte. So the first design decision is controller selection: confirm the peripheral samples SCL, or pick one that does. Note the scope: in Hs-mode (3.4 MHz) the spec doesn't permit stretching at all, so this applies to Standard (100 kHz), Fast (400 kHz) and Fast-mode Plus (1 MHz).

Design

Pick the timeout from the slowest legitimate stretch, not from the nominal bit time. A target doing an ADC conversion or a page write may hold SCL for milliseconds. Budget it: worst-case target stretch + controller overhead + margin. If the bus is SMBus, the spec already bounds this (Ttimeout is 25 ms minimum, 35 ms maximum) so 35 ms is the ceiling, not a guess. On plain I2C there's no spec number; measure the slowest device and set the timeout above it. Linux's i2c core defaults adapter->timeout to HZ (1 s) when a driver doesn't set it, which is far too long for a watchdog-guarded system.

budget itemexample
nominal byte at 400 kHz~22.5 µs
worst-case target stretch2 ms
controller/DMA overhead0.5 ms
margin2×
chosen timeout~5 ms

Recovery: when the timeout fires, don't just abort. The target may be mid-byte holding SDA. Drive 9 SCL pulses with SDA released, then issue a STOP. That flushes the target's shift register and returns the bus to idle. Then re-init the peripheral.

Trade-offs

Hardware timeout (STM32 I2C's SCL-low timeout in TIMEOUTR, NXP LPI2C's bus-idle timeout in MCFGR2) resets the peripheral in silicon and is fast, but the granularity is coarse and it can't distinguish a stuck target from a shorted bus. Software timeout in the driver is flexible and can log context, but it only fires if the driver is scheduled: a busy system can miss it. No timeout is only defensible on a dedicated bus with a known-good target and no watchdog.

Failure modes and detection

  • Controller doesn't sample SCL: silent data corruption. Detect with PEC/CRC mismatch or a NACK where you expected an ACK.
  • Target stuck forever: bus hangs, every subsequent transfer times out. Detect by the timeout firing on the first byte, not mid-transfer.
  • Timeout below worst case: intermittent failures on one slow device under load or temperature. Detect by correlating timeouts with that device's operations.
  • Watchdog shorter than the I2C timeout: watchdog resets mid-transfer. Detect via the reset-reason register.
  • Stretch misdiagnosed as a short: SCL held low permanently. Detect with a scope, if SCL never goes high even with no transaction, it's a short, not a stretch.

Validation

Scope SCL/SDA on the slowest device and measure the actual stretch. Inject a stretch with a target that holds SCL for a known time and confirm the controller waits and the timeout fires just above it. Fault-inject a shorted SCL and confirm recovery doesn't loop forever. Run it under the real watchdog.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate a serial-link strategy for I2C arbitration.

Answer

Assumptions. Multi-master bus, open-drain SDA/SCL, wired-AND, at least two masters that can issue a START inside the same bit window. I'm the SoC master on a hardware I2C controller that exposes arbitration loss as a status bit. Standard-mode 100 kHz or Fast-mode 400 kHz, Cb ≤ 400 pF.

Core answer. You don't design arbitration: it's a property of wired-AND. You design the loss-handling policy: detect the loss, release both lines within one bit time, and retry at transaction granularity with randomized backoff. Validation is a two-master rig that forces collisions.

Mechanism. A master drives SDA low or releases it (high). Every bit it transmits, it reads back. If it released SDA expecting high and reads low, another master is driving: it lost. Loss can happen on any bit it transmits: address, data, or the ACK bit it drives as a receiver. It cannot lose on START, repeated START, or STOP, because every master drives those identically. The loser must release SDA and SCL immediately and switch to slave-receive, because the winner may address it next. Clock sync is separate: tLOW = max over masters, tHIGH = min, so a 100 kHz master stretches a 400 kHz one.

Design decisions.

  • Retry the whole transaction, not the byte. A loss mid-data leaves the slave with a partial write; a repeated START or STOP resets its state machine, so re-issue from START.
  • Backoff must be randomized. Two masters with identical fixed retry delays re-collide deterministically: that's livelock, not contention. Use random in [0, 2^k × 50 µs], k = min(loss_count, 5), capped at 1.6 ms.
  • Where to retry: the Linux i2c core's __i2c_transfer() already retries on -EAGAIN up to adap->retries times, bounded by adap->timeout (default 1 s). That retry is immediate, so keep adap->retries at 1–2 and put the randomized backoff in the client driver. Alternative: backoff inside the adapter, which fixes every client at once but hides the loss count from the client.

Failure modes, detection, cost.

  • Livelock: loss rate stays high with no completed transactions. Detect by counting ARLO events per second; if >100/s with zero successful transfers, it's livelock. Cost: bus throughput collapses to zero.
  • Duplicate command: retry after a partial write to a FIFO or counter. Detect by reading back the register or a sequence number. Cost: double-push. Fix: make retried transactions idempotent, or gate non-idempotent ones behind a sequence check.
  • Generic driver error: adapter maps ARLO to -EIO instead of -EAGAIN, so the client can't tell contention from a dead bus. Detect by reading the status register: STM32 I2C_SR1 bit 9 (ARLO) vs bit 8 (BERR); NXP-style status codes 0x38 and 0x68 mean arbitration lost. Cost: retrying a dead bus forever, or abandoning a live one.
  • Noncompliant device holds SDA low: bus stuck. Detect by checking SDA/SCL idle high after STOP. Recover with up to 9 SCL pulses then a STOP. Cost: bus down until recovery.

Validation. Two masters, same target address, overlapping STARTs. Sweep the backoff seed to force collisions. Measure ARLO count, retries per transaction, and whether both transactions complete. Scope SDA/SCL to confirm the loser releases within one bit time.

Trace. Both masters send address 0x50 write, then A sends data 0x00 and B sends 0x01. They agree through START, the 8 address bits, the ACK, and data bits 7–1. At data bit 0, A drives low and B releases; B reads low and loses. 17 bit times have elapsed, about 43 µs at 400 kHz, then B releases SDA and SCL and goes to slave-receive. A finishes its ACK and STOP. B backs off a random 0–50 µs and re-issues from START.

modefSCL maxtLOW mintHIGH mintr maxCb max
Standard100 kHz4.7 µs4.0 µs1000 ns400 pF
Fast400 kHz1.3 µs0.6 µs300 ns400 pF
Fast-mode Plus1 MHz0.5 µs0.26 µs120 ns550 pF

Timing from NXP UM10204 Table 10.

C
for (int k = 0; k < 8; k++) {
    rc = i2c_transfer(adap, msgs, n);   /* -EAGAIN on ARLO */
    if (rc == n) return 0;
    if (rc != -EAGAIN) return rc;       /* real fault, don't retry */
    usleep(rand() % (50 << min(k, 5))); /* 0..50us doubling, cap 1.6ms */
}
return -EAGAIN;

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design and validate a serial-link strategy for I2C bus recovery.

Answer

First, pin down what "stuck" means. If SDA is held low and no master is driving it, a target was interrupted mid-byte and is waiting for more SCL edges. If SCL is held low, a target is clock-stretching or dead. Assume a single master, standard mode at 100 kHz, and a target with no dedicated reset line: the common case.

The core answer: switch SCL and SDA to open-drain GPIO, clock SCL nine times at ≤100 kHz, issue a STOP, re-init the controller, then probe the bus. Bound the whole attempt at 100 ms; if SDA is still low, power-cycle the target.

Why nine: a target's shift register completes a byte on eight SCL edges and drives the ACK on the ninth. After that edge it releases SDA and waits for a STOP. Fewer pulses leave it mid-byte; more just clock out garbage. Nine edges at 100 kHz is 90 µs, plus a ~10 µs STOP: about 100 µs of work, so a 100 ms timeout is a 1000× margin.

C
/* C11, gcc 13.2, Linux 6.6 gpiod uAPI */
#define RECOVERY_PULSES     9
#define RECOVERY_HALF_US    5      /* 5 us low + 5 us high = 100 kHz */
#define RECOVERY_TIMEOUT_MS 100

int i2c_bus_recover(struct bus *b)
{
    uint64_t deadline = now_ms() + RECOVERY_TIMEOUT_MS;
    int i;

    if (b->xfer_in_flight) return -EBUSY;      /* never race a transfer */

    pinmux_set(b->scl, GPIO_OD);               /* open-drain, not push-pull */
    pinmux_set(b->sda, GPIO_OD);

    if (gpio_get(b->sda) && gpio_get(b->scl))  /* bus already idle */
        goto done;

    for (i = 0; i < RECOVERY_PULSES; i++) {
        if (now_ms() > deadline) return -ETIMEDOUT;
        gpio_set(b->scl, 0); udelay(RECOVERY_HALF_US);
        gpio_set(b->scl, 1); udelay(RECOVERY_HALF_US);
        if (gpio_get(b->sda)) break;           /* target released early */
    }

    /* STOP: SDA falls then rises while SCL is high */
    gpio_set(b->sda, 0); udelay(RECOVERY_HALF_US);
    gpio_set(b->sda, 1); udelay(RECOVERY_HALF_US);

    if (!gpio_get(b->sda) || !gpio_get(b->scl))
        return -EIO;                           /* still stuck: power-cycle */

done:
    pinmux_set(b->scl, I2C_AF);
    pinmux_set(b->sda, I2C_AF);
    return 0;
}

Trace it on a stuck bus: SDA low, SCL high, no transfer in flight. Pinmux goes to open-drain; the idle check fails because SDA reads 0. The loop drives SCL low 5 µs, high 5 µs, then samples SDA. A target that was three bits into a byte releases SDA on the ninth rising edge, so the loop breaks at i=8 with SCL high. The STOP pulls SDA low then releases it while SCL is high. Both lines read high, so the function restores the I2C alternate function and returns 0. If the target never releases, the loop runs all nine pulses, the STOP cannot raise SDA, and the function returns -EIO.

Validation is a bench fixture, not a hope. Wire a spare GPIO to SDA so you can pull it low on demand, and put a logic analyzer on both lines. Four tests: (1) hold SDA low externally, run recovery, assert both lines high within 100 ms; (2) reset the master mid-byte during a real write, run recovery, then read the target's status register and confirm no partial write committed; (3) count pulses on the analyzer. Assert ≤9 and no SCL edge above 100 kHz; (4) power off the target, run recovery, assert it returns -EIO and the power-cycle escalation fires. After any recovery, re-program the controller's clock divider and read a known register to prove the bus works.

Alternatives and when to pick them: a dedicated reset line per target is cleanest but costs a GPIO and a trace; a bus switch or isolator contains a dead target but adds capacitance and BOM cost; power-cycling the whole rail is guaranteed but resets every device and loses configuration. Decide on three things: can the target's state be recovered by clocking, do other devices on the bus need to stay up, and do you have a reset line.

Failure modes, each with detection:

  • Target powered off: its ESD clamp diodes pull SDA low through the pull-up, and no number of pulses helps. Detect: SDA stays low after nine pulses and returns high only once the target is powered. Cost: bus down until power-cycle.
  • Pulse advances a write: a target mid-write treats the nine edges as a continuation and commits a partial page. Detect: read the target's status or CRC after recovery and compare. Cost: silent data corruption.
  • Multi-controller conflict: another master is driving the lines and you bit-bang against it. Detect: the controller reports arbitration lost or bus busy; the analyzer shows two drivers. Cost: contention, possible damage.
  • Wrong GPIO mode: push-pull on SDA fights a target pulling low. Detect: current on SDA spikes; check the pinmux. Cost: high current, device damage.
  • Recovery races a transfer: another thread starts a transfer while you bit-bang. Detect: assert the bus mutex is held; a bus error during recovery. Cost: corrupted transfer and a false "recovered" state.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design and validate a serial-link strategy for UART framing.

Answer

Assumptions: 8N1, point-to-point, both ends on independent clocks, receiver oversamples 16x and samples mid-bit. Change any of those and the budget changes.

Core answer. Budget the combined clock mismatch between the two ends to ≤ ±2%, pick clock sources that hold that with margin across temperature and voltage, and prove it with a bit-error-rate soak at the fastest baud and longest cable. The ±2% is not the theoretical limit: it is the limit with margin left for start-edge quantization and noise.

Why error accumulates. There is no clock line. The receiver detects the start bit's falling edge, then samples each bit at its center using its own free-running bit clock. Any frequency difference from the transmitter shifts the sample point a little more every bit, so the error grows linearly across the frame: after n bit times the sample point has drifted n·e bit times. The last bit sampled is the binding constraint.

The arithmetic. A 10-bit frame (start + 8 data + stop) samples the stop bit at 9.5 bit times. Start-edge detection quantizes to one oversample tick, 1/16 bit. To keep the sample inside the bit:

9.5·e + 1/16 ≤ 0.5   →   e ≤ 4.6%

So the theoretical ceiling is ~4.6% total mismatch; the ±2% design rule leaves roughly 2x margin for jitter, noise and asymmetric rise/fall. Sampling only the last data bit (8.5 bit times) raises the ceiling to ~5.1%, not enough to change the rule.

Clock sources.

sourcetolerancenotes
crystal±10–50 ppm0.001–0.005%; needs a divisor that divides cleanly
ceramic resonator±0.1–0.5%fine for short frames, cheap
internal RC±1–3% over temp/Vccmarginal; only with short frames or autobaud
trimmed RC±1%ok if both ends trimmed and temperature is controlled

Baud divisor error is separate and often the real killer. With 16 MHz and 115200 baud at 16x oversampling:

C
uint32_t div    = (16000000 + 8*115200) / (16*115200);  // = 9
uint32_t actual = 16000000 / (16*div);                  // = 111111
// error = (111111 - 115200) / 115200 = -3.5%

−3.5% alone blows the ±2% budget before any oscillator error. A 7.3728 MHz crystal divides exactly (divisor 4), which is why it exists. Otherwise use a fractional baud generator or a higher clock.

Trade-offs. Crystal when frames are long, baud is high, or the link is multi-drop. Internal RC only when frames are short and you can autobaud or tolerate retries. 9-bit multiprocessor framing cuts per-byte overhead but does not change the clock budget.

Failure modes and how to catch them.

  • Wrong divisor → framing error on every byte; the error flag is set consistently.
  • Drift over temperature → errors only at corners; catch with a soak across the full temp range.
  • Inverted transceiver (RS-232 levels into a TTL pin) → no start edge, receiver sees idle; catch on a scope.
  • Parity mismatch → parity error, not framing error; the two flags separate the causes.
  • Break (line held low) → receiver reads all-zero bytes; catch with the break-detect flag.
  • Cable noise → random bit errors; catch with a CRC at a higher layer.

Validation. Loopback at min/max Vcc and temp corners, 10^7 pseudorandom bytes, count framing and parity errors, target BER < 1e-6. Scope the start edge and confirm sample points sit mid-bit at the worst corner. Repeat at max baud and max cable length.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate a serial-link strategy for UART packetization.

Answer

Core answer (first 90 seconds)

Assume a point-to-point UART link, 8N1, 115200 baud, MCU-to-MCU or MCU-to-host, no hardware flow control, and a byte stream that can drop or corrupt bytes across a reset. UART gives you start and stop bits per byte and nothing else: no message boundary, no length, no checksum. The framing layer has to supply all three, and it has to recover from a mid-stream desync without a reboot.

My default: COBS framing with a 0x00 delimiter, plus a CRC-16 over the decoded body. Frame = 0x00 | COBS(body) | 0x00, body = [ver:1][type:1][seq:2][len:2][payload:0..247][crc16:2]. COBS guarantees the encoded body contains no 0x00, so the delimiter is unambiguous and the parser resynchronizes on the next 0x00 after any corruption. Worst-case overhead is one byte per 254-byte block.

Why it behaves that way

Length-prefixed framing without a delimiter is the trap. If the length field is corrupted, the parser reads N bytes that don't exist, swallows the next frame's header as payload, and stays locked until something resets it. Escaping or COBS removes that failure: the delimiter is the only resync point, and it cannot appear inside a frame.

Timeout framing (Modbus RTU's 3.5-character idle gap) works only when the inter-byte gap is stable. Over USB-serial or with an RTOS that preempts the ISR, a valid frame can be split by a gap longer than the threshold and get truncated. Don't make timeout the primary boundary; use it only as a stall detector.

Choosing among options

SchemeBoundaryResync after corruptionOverheadUse when
Length-prefix + magiclength fieldmagic scan + timeout0fixed peers, both ends controlled
Delimiter + escaping (SLIP)0xC0 ENDnext 0xC0up to 2x worst caselegacy, simple
COBS + 0x000x00next 0x00≤1 byte/254default for new designs
Idle-timeoutinter-byte gapnext gap0Modbus RTU compat only

Failure modes and detection

  • Delimiter in payload: COBS/escaping removes it; test by fuzzing payloads full of 0x00.
  • Corrupt length: with COBS the parser never trusts a length to find the next frame; it resyncs on 0x00. Detect via CRC failures counted per port.
  • Unbounded allocation: cap the receive buffer at max frame (256 bytes here) and drop on overflow; assert on it in debug builds.
  • Reboot mid-frame: the partial frame is discarded at the next 0x00; no parser state survives reset.
  • Timeout splits a slow frame: only if timeout is the boundary. Another reason not to use it.

Validation

Arithmetic: at 115200 8N1, 10 bits/byte → 11520 B/s. A 256-byte frame is 256×10/115200 ≈ 22 ms, so worst-case resync is one frame ≈ 22 ms.

Trace the decoder on body {0x11, 0x00, 0x22}: COBS encodes it to {0x02, 0x11, 0x02, 0x22}. Decode reads code 0x02, copies 0x11, emits 0x00; reads code 0x02, copies 0x22, end of input so no trailing 0x00 → {0x11, 0x00, 0x22}. Round-trips.

Tests: (1) property test. Random byte streams, assert the parser never allocates >256 bytes and always resyncs within one frame; (2) fault injection. Flip one byte per frame, count CRC rejects, confirm the next frame parses; (3) HIL loopback at 115200 with a deliberate mid-frame reset, confirm recovery on the next delimiter.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate a serial-link strategy for UART errors.

Answer

I'd start by scoping the link: 115200 8N1, an MCU UART with per-byte status flags (STM32 USART is the concrete example), DMA for RX, and an interrupt for errors and IDLE. If your link is different, the same three-part design applies but the register names change.

The design is: latch status with data, discard and count on error, resynchronize on idle. Validation injects each error type and checks the counters and that no bad frame reaches the application.

Why latch status with data. On STM32, USART_SR holds ORE, NE, FE, PE for the byte currently in DR. If you read DR first, the error flags may be cleared or overwritten by the next byte. The ISR must read SR then DR in that order. That single read pair both clears the flags and gives you the byte and its error state.

C
void USART1_IRQHandler(void) {
    uint32_t sr = USART1->SR;
    uint8_t  dr = USART1->DR;
    if (sr & (USART_SR_ORE | USART_SR_NE | USART_SR_FE | USART_SR_PE)) {
        error_count[sr & 0x0F]++;
        frame_invalid = 1;
        return;
    }
    if (frame_invalid) return;
    rx_buf[rx_head++] = dr;
}

Trace. Byte A clean: SR=0x20, DR=A → stored. Byte B framing error: SR=0x0A, DR=B → error_count[FE]++, frame_invalid=1, B discarded. Byte C clean: SR=0x20, DR=C → frame_invalid still 1, C discarded. IDLE: SR=0x10 → clear frame_invalid, reset buffer. Next byte accepted.

Trade-offs. Interrupt-per-byte is simple, but at 921600 baud the byte time is 10.85 µs; an ISR that logs to a slow UART will overrun. DMA with an error interrupt is the alternative: DMA moves data, and you enable the UART error interrupt (or use the DMA error flag) to catch ORE/FE. Cost: DMA hides the per-byte status unless you also read SR in the error ISR. Deciding criterion: if baud > ~500 kbaud or you have other real-time work, use DMA + error interrupt; otherwise polled or interrupt-per-byte is fine.

Failure modes.

  • Status cleared before read: reading DR first loses the error association.
  • Error assigned to wrong byte: reading SR in a later ISR.
  • DMA hides flag: no error interrupt enabled, ORE silently drops bytes.
  • Stale partial frame: not flushing the buffer after error, so old bytes mix with new.
  • Counter floods logs: rate-limit error logging, e.g., log first 10 then every 1000th.

Validation. Inject each error. For framing, drive TX low during the stop bit (use a signal generator or a second UART with 1.5 stop bits). For overrun, stop reading for 200 µs at 115200 (byte time 86.8 µs). For noise, inject a glitch. Check: error counters increment exactly once per injection; no corrupted frame reaches the application; resync time < 2 byte times. Use a logic analyzer to confirm the IDLE-based resync.

ErrorFlagCauseAction
OREOverrunNew byte before DR readDiscard, count, resync
FEFramingStop bit lowDiscard, count, resync
NENoiseGlitchDiscard, count, maybe resync
PEParityParity mismatchDiscard, count, resync

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate a serial-link strategy for timeouts.

Answer

One timer is never enough. I'd design three, and size each from the datasheet rather than an average.

Take a UART at 115200 8N1: 10 bits per byte, so 86.8 µs per byte: talking to a device whose datasheet gives 20 ms worst-case processing. The three timers:

  • Inter-byte timeout delimits the frame: 3.5 character times, the framing rule Modbus RTU is built on, which at 115200 is 304 µs. Round to 500 µs. (Modbus itself fixes t3.5 at 1.750 ms above 19200 baud; for a private link, 3.5 char times is the right shape.)
  • Response deadline runs from end-of-transmit to the first response byte: device worst case 20 ms plus jitter margin, so 30 ms.
  • Transaction deadline is absolute and includes retries: request TX (8 bytes = 694 µs) + 30 ms + response RX (64 bytes = 5.56 ms) ≈ 36 ms, rounded to 50 ms. Two retries → 150 ms worst case, which must fit the caller's budget.

Why three and not one: a single deadline can't tell a truncated frame from a slow device. The inter-byte timer fires in 500 µs when the peer resets mid-frame; the response deadline fires in 30 ms when the device is hung. Different faults, different recovery.

Mechanism: wrap-safe deadlines. Don't compare against an absolute counter; compare a signed difference so the 32-bit rollover is free:

C
/* 1 ms tick, 32-bit free-running counter */
static bool expired(uint32_t now, uint32_t deadline) {
    return (int32_t)(now - deadline) >= 0;   /* wrap-safe */
}

Trace: now = 0xFFFFFF00, deadline = 0x00000100. now − deadline = 0xFFFFFE00; as int32_t that's negative, so not expired: correct, the deadline is 256 ticks ahead.

Cancellation and recovery. On timeout you must abort, not just stop waiting. Disable the DMA channel, drain the RX FIFO, and on RS-485 release the driver-enable line. On I2C a slave holding SDA low needs nine clock pulses to recover. Only after the abort is confirmed may you free the buffer.

Late callbacks. The completion ISR can fire after you've timed out and freed the buffer. Tag every transfer with an epoch and drop mismatches:

C
static volatile uint32_t g_epoch;
static void rx_done(void *buf, size_t n, uint32_t epoch) {
    if (epoch != g_epoch) { g_late++; return; }  /* aborted transfer */
    ...
}

Trade-offs. A tight deadline catches faults fast but false-trips on a busy scheduler; a loose one wastes caller latency. I size from datasheet worst case plus measured jitter, not from the mean. Alternative: a single watchdog that resets the port on any timeout. Simpler, but it can't distinguish a truncated frame from a hung device, so it recovers slower and loses the diagnostic.

Failure modes and detection.

failuredetection
timer wrapwrap-safe compare; test by seeding counter near 2³²
late callbackepoch mismatch counter (g_late)
buffer freed earlyassert epoch still current before free
abort incompletecheck DMA enable bit cleared before restart
retry overlaps old transferrequire RX idle > t3.5 before retry

Validation. Fault injection, not unit tests alone. Short RX to ground mid-frame → inter-byte timer must fire in ≤500 µs. Delay the device past 30 ms → response deadline fires, one retry, recovery. Hold SDA low → nine-pulse recovery completes. Seed the counter near 2³² → no spurious expiry. Measure time from fault to a clean next transaction; that number, not the timeout value, is what you put in the runbook.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate a serial-link strategy for interrupt completion.

Answer

Core answer (first 90 seconds). Assume 8N1 UART, 115200 baud to 1 Mbaud, frames of 32–256 bytes, an RTOS, and a DMA-capable USART (STM32F4-class). The strategy: DMA moves bytes into a circular buffer; the UART IDLE-line interrupt marks frame end; the ISR does O(1) work and posts a length to a queue; a task parses. Completion is emitted exactly once per frame, from the IDLE handler, after the status flags are cleared in the order the reference manual requires.

Why not per-byte interrupts. At 115200 baud, 8N1 is 10 bits/byte → 11,520 bytes/s. At 1 Mbaud, 100,000 bytes/s. A 5 µs ISR per byte costs 50% of a 100 MHz core at 1 Mbaud, and the ISR must also clear RXNE. DMA+IDLE turns that into one interrupt per frame: at 64-byte frames and 1 Mbaud, 1,562 interrupts/s.

The ISR. STM32F4 USART2 + DMA1 Stream5, circular, 256-byte buffer:

C
#define BUF_SZ 256
static uint8_t rx_buf[BUF_SZ];
static volatile uint16_t last_head;

void USART2_IRQHandler(void) {
    if (USART2->SR & USART_SR_IDLE) {
        (void)USART2->SR;          // read SR
        (void)USART2->DR;          // then DR clears IDLE
        uint16_t head = BUF_SZ - DMA1_Stream5->NDTR;
        uint16_t len  = (head - last_head + BUF_SZ) % BUF_SZ;
        if (len) {
            osMessageQueuePut(rx_q, &head, 0, 0); // head only; consumer reads buf
            last_head = head;
        }
    }
    if (USART2->SR & USART_SR_ORE) {
        (void)USART2->DR;          // clear overrun
        overrun_count++;
    }
}

The ISR is O(1): two register reads, one modulo, one queue put. No parsing, no memcpy. The consumer reads rx_buf[last_consumed..head) and must finish before the DMA wraps; if head would overtake last_consumed, that is a lost-frame condition, counted and reported.

Validation. Three tests, each with an acceptance criterion:

testmethodaccept
worst-case ISRtoggle GPIO at ISR entry/exit, scope, or DWT->CYCCNT at 168 MHz< 1,680 cycles (10 µs)
line-rate integrityback-to-back 64-byte frames at 1 Mbaud, 10^6 framesORE count = 0, no lost frames
IDLE storminject 1 µs glitch on RX, count ISRs/s< 2× frame rate; enable USART_CR3 ONEBIT if exceeded

Trade-offs.

schemeISR rate at 1 MbaudCPU costwhen it flips
poll RXNE in task0latency = task periodonly if baud < ~9600 and no RTOS
per-byte RXNE IRQ100,000/s~50% at 5 µs ISRsmall frames, no DMA, low baud
DMA + IDLE1,562/s at 64 B< 1%default for framed protocols
DMA + RX timeout1,562/s< 1%when IDLE is unreliable (noisy line)

Failure modes and detection.

  • Interrupt storm: IDLE fires on every noise glitch. Detect by counting ISRs/s; if > 2× frame rate, enable the USART ONEBIT sample filter or add a minimum-gap timer.
  • Missed status-clear order: IDLE is cleared only by reading SR then DR. If the code reads DR first, IDLE stays set and the ISR re-enters forever. Detect by watching the ISR entry count against frame count.
  • Callback reentrancy: the completion callback runs in ISR context and also from a task. Detect with an atomic in_callback flag; assert if set on entry.
  • Task API misuse: calling a blocking queue put from the ISR. Detect by asserting __get_IPSR() != 0 in the blocking path, or use osMessageQueuePut(..., 0) only.
  • Completion emitted twice: IDLE and DMA TC both fire for one frame. Detect by tagging each completion with the frame sequence number and asserting monotonicity.

When not to use this. If frames are fixed-length and the DMA count is known, skip IDLE and use DMA TC alone: one less interrupt source. If the line is half-duplex with a driver-enable turnaround, IDLE can fire on the echo; gate the IDLE handler on the receive-enable state.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate a serial-link strategy for DMA ownership.

Answer

Assumptions I'd state up front: STM32F4/H7-class MCU, USART TX, memory→peripheral DMA, half-duplex RS-485 with a driver-enable (DE) pin. If you're full-duplex with a pool of buffers, the design simplifies: say so and move on.

Core answer. There are two completion boundaries, not one, and they protect different resources.

  • DMA transfer-complete (TCIF in DMA_LISR/DMA_HISR) means the last byte has been written into USART_TDR. Memory reads are finished, so the buffer is yours again. The line is not idle.
  • USART transmission-complete (TC in USART_ISR) means the last frame has fully shifted out. Only now is the line idle: safe to drop DE, gate the USART clock, or start the next half-duplex transfer.

So ownership is a four-state machine, and each state names who may touch the buffer and what the line is doing:

stateentered bybuffer ownerline
IDLEreset, or app ackappidle
QUEUEDtx_start arms DMADMAbusy
DMA_DONEDMA TCIFappstill shifting
WIRE_DONEUSART TCappidle

With raw DMA/LL you must wire both interrupts yourself; HAL collapses them: HAL_UART_Transmit_DMA enables UART_IT_TC from the DMA-TC callback and only then calls HAL_UART_TxCpltCallback, so that callback is wire-complete, not DMA-complete. That distinction is exactly what breaks when someone drops to LL and assumes "DMA done = buffer free = line free."

C
static volatile tx_state_t st = IDLE;
static uint8_t *tx_buf;

void tx_start(uint8_t *buf, size_t n) {
    if (st != IDLE) return;                 /* one outstanding transfer */
    tx_buf = buf; st = QUEUED;
    LL_DMA_SetDataLength(DMA1, LL_DMA_STREAM_6, n);
    LL_DMA_SetMemoryAddress(DMA1, LL_DMA_STREAM_6, (uint32_t)buf);
    LL_DMA_EnableIT_TC(DMA1, LL_DMA_STREAM_6);
    LL_USART_EnableIT_TC(USART2);           /* arm wire-complete now */
    LL_DMA_EnableStream(DMA1, LL_DMA_STREAM_6);
}

void DMA1_Stream6_IRQHandler(void) {        /* DMA TC: buffer free */
    if (LL_DMA_IsActiveFlag_TC6(DMA1)) {
        LL_DMA_ClearFlag_TC6(DMA1);
        LL_DMA_DisableStream(DMA1, LL_DMA_STREAM_6);
        st = DMA_DONE;                      /* tx_buf reusable here */
    }
}

void USART2_IRQHandler(void) {              /* USART TC: line idle */
    if (LL_USART_IsActiveFlag_TC(USART2)) {
        LL_USART_ClearFlag_TC(USART2);
        LL_USART_DisableIT_TC(USART2);
        LL_GPIO_ResetOutputPin(DE_PORT, DE_PIN);   /* now safe */
        st = WIRE_DONE;
    }
}

Trace it. A 64-byte frame at 115200 8N1 is 10 bits/byte = 86.8 µs/byte, 5.56 ms total. TDR is one byte deep and TXE only sets when TDR hands off to the shift register, so DMA cannot run ahead of the wire: TCIF fires when byte 64 lands in TDR, at 63 × 86.8 µs ≈ 5.47 ms. TC fires one byte time later, ≈ 5.56 ms. The window between them is exactly one byte time: 86.8 µs at 115200, but 1.04 ms at 9600. That window is where a task that drops DE on the DMA callback truncates the last byte.

Trade-offs. Releasing the buffer at TCIF and gating line control on TC is the right default. Waiting for TC before releasing the buffer is simpler and costs up to one byte time of pipeline latency per frame: fine at 115200, painful at 9600. Polling TC in a busy loop is the one to reject: it blocks the caller for a full byte time and starves an RTOS. Deciding criterion: if anything outside the USART depends on the line being idle (DE, clock gating, half-duplex turnaround), you need TC; if you only need the buffer back, TCIF is enough.

Failure modes and how you catch them.

  1. Buffer mutated before TCIF: DMA still reading memory. Symptom: intermittent checksum failures that scale with CPU load. Catch it with a CI canary: fill the buffer with 0xA5, start the transfer, immediately overwrite with 0x5A, and assert the receiver sees 0xA5.
  2. DE dropped at TCIF: last byte truncated. Symptom: receiver framing error or a short frame. Catch it by scoping DE against TX and counting bytes at the receiver.
  3. USART disabled before TC: clock gated or HAL_UART_DeInit while TC=0 loses the final byte. Symptom: last byte missing, TC never observed. Assert TC before deinit.
  4. Callback-order race: TxCpltCallback runs in ISR context; if it returns the buffer to a pool and a higher-priority task re-arms immediately, the allocator must be ISR-safe. Symptom: rare double-use or heap corruption.
  5. Cancellation leaves DMA active: after HAL_UART_AbortTransmit, confirm the stream's EN bit in DMA_SxCR has cleared before re-arming, or the next HAL_UART_Transmit_DMA returns HAL_BUSY. Catch it by reading EN in the abort path.

Validation procedure: scope DE, a GPIO toggled in the DMA-TC ISR, and a GPIO toggled in the USART-TC ISR against TX; the two toggles must be one byte time apart with DE falling only after the second. Then run the canary test and the abort-then-rearm test in CI.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate a serial-link strategy for DMA cache coherence.

Answer

Assumptions. ARM64 Linux host, PCIe endpoint that does not snoop CPU caches (no CXL.cache or CCIX), 64-byte cache lines, streaming DMA of a 1500-byte frame. The device and CPU must agree on buffer contents, and I have to prove it.

Core answer. Use the kernel DMA API rather than hand-rolled cache maintenance. dma_map_single() hands ownership to the device and does the direction-appropriate cache work; dma_unmap_single() hands it back. The CPU must not touch the buffer between the two calls. Order the descriptor write before the doorbell with dma_wmb(), and the completion read before the payload read with dma_rmb(). Validate with a pattern test and a PCIe analyzer.

Why it works. A cache line can hold dirty CPU data the device never sees, and after the device writes memory the CPU cache can still hold the old copy. Mapping cleans (writes back) for device-read directions and invalidates (drops) for device-write directions, so neither side reads stale data.

Directiondma_map_singledma_unmap_single
DMA_TO_DEVICEcleanno-op
DMA_FROM_DEVICEinvalidateinvalidate
DMA_BIDIRECTIONALcleaninvalidate

The invalidate on map for DMA_FROM_DEVICE matters: it drops dirty lines that would otherwise be written back over the device's data.

C
/* ARM64 Linux, non-coherent PCIe endpoint, 64-byte lines.
   buf is cache-line aligned (kmalloc on ARM64 is ARCH_DMA_MINALIGN-aligned). */
#define FRAME 1500
u8 *buf = kmalloc(FRAME, GFP_KERNEL);

/* TX: CPU -> device */
dma_addr_t h = dma_map_single(dev, buf, FRAME, DMA_TO_DEVICE);   /* clean */
if (dma_mapping_error(dev, h)) { kfree(buf); return -ENOMEM; }
writel(h, bar + TX_DESC);
dma_wmb();                       /* descriptor visible before doorbell */
writel(1, bar + TX_DOORBELL);
/* poll TX_DONE */
dma_unmap_single(dev, h, FRAME, DMA_TO_DEVICE);                  /* no-op */

/* RX: device -> CPU */
h = dma_map_single(dev, buf, FRAME, DMA_FROM_DEVICE);            /* invalidate */
writel(h, bar + RX_DESC);
dma_wmb();
writel(1, bar + RX_DOORBELL);
/* poll RX_DONE */
dma_unmap_single(dev, h, FRAME, DMA_FROM_DEVICE);                /* invalidate */

writel() already carries an I/O write barrier on ARM64; dma_wmb() states the intent and is required if the doorbell uses a relaxed accessor.

1500 bytes spans ceil(1500/64) = 24 lines. 23 lines cover 1472 bytes; the 24th holds the last 28 bytes of the frame plus 36 bytes of whatever follows. If the buffer is aligned, that tail is inside the same allocation, but invalidating it discards any dirty neighbour data there.

Failure modes.

  • Unaligned buffer sharing a line. Invalidate drops a neighbour's dirty data. Detect: put a sentinel in the 36 bytes after the frame, DMA 1500 bytes, check the sentinel. Cost: silent corruption of unrelated memory.
  • Wrong direction. Mapping an RX buffer as DMA_TO_DEVICE skips the invalidate, so the CPU reads stale cache. Detect: device writes a known pattern; CPU reads without unmap and sees old bytes.
  • Missing barrier before the doorbell. Device reads a stale descriptor. Detect: alternate the descriptor's buffer address and watch which one the device uses.
  • Completion read reordered before data. Poll loop without dma_rmb() returns before the payload lands. Detect: vary payloads under load and compare.

Validation. Fill the buffer with a counter pattern, DMA out, have the device invert it, DMA back, compare. Run the unaligned and 1500-byte edge cases. Watch real transactions on a PCIe analyzer, and read cache-maintenance counters to bound the overhead.

Alternatives. A coherent interconnect (CXL.cache, CCIX, or on-chip ACE via CCI-400/CCN) removes the maintenance but needs hardware support. dma_alloc_coherent() gives a permanently coherent buffer with no per-transfer work, at the cost of uncached CPU access. An IOMMU gives translation and protection, not coherence: ATS caches translations, it does not make the device snoop.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate a serial-link strategy for retry safety.

Answer

Assumptions. Point-to-point UART or RS-485 to a device with a register map. Host timeout is tens of milliseconds; the link can drop a reply without dropping the request. Under those conditions a timeout means the outcome is unknown: the frame may never have arrived, may have been applied with the ACK lost, or may have been applied partially. Treating timeout as failure is the bug.

Core answer. A retry is safe only if the operation is idempotent, or the device can tell a duplicate from a new request. Pick the mechanism from what the device gives you, then prove it with fault injection.

Choosing the mechanism.

mechanismneeds from devicesafe whenbreaks when
Absolute writenothingvalue is absolute (setpoint = 1500)command is relative (increment, pulse)
Sequence number + dedupestores last-seen seqseq survives the retry windowdevice reboots, seq in RAM resets
Read-back verifyregister reflects the effecteffect is persistent and observableeffect is transient, or old value equals new
Commit-status registerexposes ack/commit bitfirmware acks commit, not receiptack means "frame parsed" only

Absolute writes are the cheapest and need no device support: prefer them whenever the command can be expressed as a target state. Sequence numbers are the general answer but only as durable as the device's storage of the last sequence. Read-back is the fallback when you cannot change the device, and it is exactly where pulses and no-op writes fool you.

Failure modes and how you catch them.

  • Duplicate actuator pulse: a "pulse valve 50 ms" retried fires twice. Detect by counting actuations on a scope or a device-side counter, not by reading the register.
  • EEPROM pointer advanced: "write record, increment pointer" retried writes two records. Detect by comparing record count to command count.
  • Partial register write: a multi-byte write torn by a timeout mid-frame leaves half the value. Detect by writing a known pattern and reading back all bytes.
  • Reboot loses dedupe: seq stored in RAM resets to 0, so a retry looks new. Detect by power-cycling the device inside the retry window.
  • Retry reorders: retry of command N lands after N+1. Detect by logging device-side arrival order.

Validating it. Inject the fault, don't reason about it. Kill the link after the request is sent but before the reply, then check the observable effect.

Trace, RS-485 at 115200 8N1 (10 bits/byte → 8-byte frame ≈ 0.7 ms), host timeout 50 ms:

  1. t=0: host sends WRITE seq=7, reg 0x10 = 1500.
  2. t=0.7 ms: frame fully on the wire; device applies it and replies ACK seq=7.
  3. Reply is lost. t=50 ms: host times out. Outcome unknown.
  4. Host retries WRITE seq=7.
  5. Device sees seq=7 equals last applied, replies ACK seq=7 without re-applying.
  6. Setpoint applied exactly once.

Now repeat with a power-cycle between steps 3 and 4. If last_seq lived in RAM, step 5 re-applies and the setpoint is written twice: the test that catches the reboot hole. Run the same harness for the pulse command and the EEPROM append; those are the two that read-back cannot save.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate a serial-link strategy for integrity.

Answer

Assumptions I'd state before designing. Point-to-point UART at 1 Mbit/s between two MCUs, frames up to 1 KB, and the cable and connector are reachable by a technician, so an adversary with a $20 USB-serial adapter is in scope. No confidentiality requirement. If the link is a sealed board-to-board trace, drop the MAC and keep the CRC.

The answer: two mechanisms, not one. CRC-32/ISO-HDLC (poly 0x04C11DB7, reflected, init and xorout 0xFFFFFFFF) over header plus payload catches random channel errors. Every burst up to 32 bits, and residual undetected probability at most 2^-32 for longer random errors. It is linear, so anyone who can write bytes can compute a valid CRC; it is not integrity against a person. Authenticity comes from HMAC-SHA-256 (RFC 2104) truncated to 64 bits, which gives 2^-64 forgery probability per attempt. Replay comes from a 32-bit sequence number plus a sliding window; RFC 4303 uses a 64-bit sequence and a window of at least 32, and 64 is a fine default.

Frame on the wire: SOF(1) | len(2, big-endian) | seq(4) | payload(len) | crc32(4) | tag(8) | EOF(1).

C
#define MAX_FRAME 1024
#define HDR 7        /* SOF(1) + len(2) + seq(4) */
#define TRAILER 13   /* crc32(4) + tag(8) + EOF(1) */

int rx_frame(const uint8_t *b, size_t n) {
    if (n < HDR + TRAILER) return -1;
    uint16_t len = (b[1] << 8) | b[2];        /* big-endian on the wire */
    if (len > MAX_FRAME) return -1;           /* bounds check before any allocation */
    if (n != HDR + len + TRAILER) return -1;
    uint32_t crc = crc32_iso_hdlc(b, HDR + len);      /* header + payload */
    if (crc != rd32be(b + HDR + len)) return -1;      /* cheap reject first */
    if (!hmac_sha256_verify(b, HDR + len + 4, b + HDR + len + 4, 8)) return -1;
    if (!seq_accept(rd32be(b + 3))) return -1;        /* anti-replay window */
    return dispatch(b + HDR, len);
}

For a 256-byte payload, n is 276 and the CRC covers 263 bytes.

Why both. MAC-only works, but you pay SHA-256 on every frame and lose the ability to tell line noise from tampering in telemetry. CRC-only is right when the link is physically protected. If you already have an AES accelerator, CMAC-AES (NIST SP 800-38B) is cheaper than software SHA-256.

Arithmetic. BER 1e-6, 276-byte frame = 2208 bits, so frame error rate is about 2.2e-3. Undetected is at most 2.2e-3 x 2^-32, about 5.1e-13 per frame. At 1 Mbit/s that is roughly 453 frames/s, so one undetected corruption every ~137 years. The MAC, not the CRC, is what stops a deliberate forgery.

Validation. Known-answer tests first: crc32_iso_hdlc("123456789") == 0xCBF43926, and HMAC-SHA-256 against RFC 4231 test case 1. Then a fault injector on the wire: bit flips at a swept BER, truncation, duplication, reordering, length-field mutation, and replay of captured frames. Measure undetected error rate against the 5.1e-13 prediction, and false rejection rate, which should track the frame error rate. Finish with a 24-hour soak at 1 Mbit/s against a noise generator.

Failure modes and how each is caught.

failurehow it shows updetection
CRC scope excludes the length fieldlength mutated, CRC still passes, receiver allocates 64 KBmutate len in the injector; assert reject before allocation
byte order mismatchCRC computed over host-order bytes, every frame rejectedKAT: crc32("123456789") == 0xCBF43926
length used before bounds checkoversized allocation or crash from a 2-byte fieldfuzz len 0..0xFFFF; assert no allocation above MAX_FRAME
unauthenticated commandvalid CRC, wrong tag, command executesinject CRC-valid, tag-invalid frame; assert reject
stale valid frame replayedan old command re-executescapture and replay; assert the sequence window rejects it and the counter never decreases

Cost note, labelled as an estimate: table-driven CRC-32 runs near 1 cycle/byte, while software SHA-256 on a 100 MHz Cortex-M4 is on the order of 10-20 cycles/byte, so a 263-byte frame costs roughly 4 kcycles, about 40 us.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate a serial-link strategy for logic-analyzer validation.

Answer

Clarify first. "Validate a serial link" splits two ways: prove the DUT's link is correct, or prove the logic analyzer's capture of it is trustworthy. I'll assume the second, the analyzer is the instrument under test, because that's where the failure modes live. Assumptions: SPI at 24 MHz, 3.3 V CMOS, one master and one sensor, an 8-channel analyzer with a 500 MSa/s ceiling.

Core answer. A capture is evidence only if three things are pinned: the electrical load it imposes, the time base it shares with firmware, and the decode settings that turn edges into bits.

Setup. Sample at 500 MSa/s, at least 5× the ~175 MHz bandwidth of a 2 ns edge, threshold at 1.65 V mid-rail, and use a short ground spring, not a 10 cm lead. A 10 pF probe on a 50 Ω source adds τ = RC = 0.5 ns of rise time, fine against a 2 ns edge; a 20 pF probe doubles that and can push setup/hold over the limit.

Correlation. Firmware toggles a spare GPIO at transaction start; capture it on channel 8. That edge aligns wire time to firmware time to within one sample (2 ns) plus channel-to-channel skew (under 1 ns). Firmware log timestamps alone are useless here: a 1 ms RTOS tick is 24,000 SPI clocks of ambiguity.

Trigger. Qualify on chip-select falling edge and use segmented capture (1000 segments × 1 ms) so 500 MSa/s × 8 channels doesn't exhaust memory in two seconds.

Validation. Capture golden transactions, then inject known faults (a dropped byte, a CPHA flip, a 2× baud error) and confirm the decode flags each one.

Failure modes.

FailureMechanismDetection
Probe loading20 pF probe adds ~1 ns rise, eats setup marginCompare edge rise with probe on vs off
Ground lead~100 nH lead rings, false clock edgesSwap to ground spring, re-capture
Sampling too slow24 MHz clock aliased at 50 MSa/sRaise to 500 MSa/s; decode changes
Decoder wrongCPOL/CPHA or bit-order mismatchDecode against known golden bytes
Clock uncorrelated1 ms tick vs 2 ns wireGPIO marker edge
Encrypted payloadCiphertext mimics valid framingOnly framing and timing are checkable

Trade-offs. A dedicated protocol analyzer decodes in hardware with far less memory pressure, but gives no analog edge visibility. Deciding criterion: marginal levels or ringing → scope with a proper probe; wrong bits or framing → logic analyzer. Don't use the logic analyzer to judge signal integrity, and don't use the scope to judge protocol correctness.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate a serial-link strategy for transaction evidence.

Answer

Assumptions first, because the question is only decidable once the link is pinned down. I'll take a half-duplex RS-485 multidrop at 115200 8N1: 10 bits per byte, so 11.5 kB/s: one master polling up to 32 nodes, and "transaction evidence" meaning a per-transaction record the host can reconstruct after a node power-cut. If your link is a point-to-point UART with no shared bus, the arbitration and turnaround parts drop out and the rest stands.

Core answer. Design the frame so every byte is attributable to exactly one transaction and one disposition, then validate by fault injection against stated acceptance criteria rather than by reading the code.

fieldbytespurpose
SOF1 (0x7E)frame delimiter
len1payload length, 0–64
seq2per-link monotonic, wraps at 65536
txn_id4idempotency key, monotonic per transaction
flags1bit0 evidence-complete, bit1 retry
payload0–64the evidence record
crc2CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF) over len..payload

Max frame is 75 bytes: 6.5 ms at 115200, 78 ms at 9600. Escape 0x7E and 0x7D as 0x7D XOR 0x20 (PPP async framing, RFC 1662); worst case doubles the payload, so budget 13 ms per frame at 115200.

CRC-16/CCITT-FALSE detects all single-bit, all double-bit, all odd-bit errors and all bursts up to 16 bits, missing 1 in 65536 longer bursts. That is the number you quote when someone asks why not CRC-32: CRC-32 costs two more bytes and a 4× table to extend burst coverage to 32 bits.

Validate. Three tests, each with a pass condition:

  1. Soak with injected corruption. 10^9 frames, bit-flip rate 1e-6, assert zero undetected corruption: verify by recomputing CRC and checking the residue, not by trusting the receiver.
  2. Fault matrix. Truncate mid-payload, duplicate a frame, reorder two frames, drop the ack, cut power during the NVM write. Pass: every txn_id is present exactly once, or absent with a logged gap. Never present twice with different payloads.
  3. Wrap arithmetic. A 16-bit seq at 100 frames/s wraps every 655 s. If a node can be offline longer than your dedupe window, the seq is not a safe idempotency key: use the 32-bit txn_id and size the window to the maximum retry lifetime.

Trade-offs. Ack-per-frame is simple and costs ~50% overhead at 64-byte payloads; a sliding window recovers throughput at the price of reorder handling. Store-and-forward survives link loss but needs NVM wear management; streaming is cheaper but loses evidence on a cut. Don't use ack-per-frame on a link that already has a reliable transport underneath: you'll double the retry logic and hide which layer failed.

Failure modes and detection.

  • Success before wire completion: the app marks a transaction done when bytes enter the UART FIFO. Detect by comparing app-complete count against peer-ack count; fix by completing only on ack.
  • Peer ambiguity: the ack is lost, the sender retries, the peer executes twice. Detect duplicate txn_id at the peer; fix with the idempotency key.
  • Counter wrap: seq is reused and dedupe silently drops a legitimate frame. Detect a gap in txn_id; fix with the 32-bit id.
  • Retry hidden: link-layer retries mask a flapping cable. Expose retry count as a counter and alert on its rate.
  • Configuration drift: a firmware update changes baud or parity. Detect a CRC-error-rate spike; fix with a versioned config fingerprint in the handshake.
  • Recovery loses the triggering status: a torn NVM write. Detect with a CRC on the evidence record itself; fix with two slots and a commit marker.

Curated: · Written: · Reviewed:

Difficulty: Hard