Stuck buses, stuck pins and drifting clocks
Freeing a locked I2C bus, detecting stuck pins, UART clock budgets and a timeout on every wait.
When the bus itself fails
The previous lesson's faults hit the MCU. This lesson's hit the wires around it, and they are more common: in field-return statistics, connectors, cables and the devices on a bus fail far more often than the MCU does. Three failures matter most because firmware can detect and often fix them: a stuck I2C bus, a stuck pin, and a clock that drifts.
The stuck I2C bus
I2C has no reset line. Each device follows the bus with a small state machine, and if the master stops talking in the middle of a byte (because it reset, browned out, or hit a breakpoint) the slave is left half way through it. If it was sending a 0 bit when the clocks stopped, it holds SDA low and waits for the next clock that never comes.
Now the bus is dead. A START is SDA falling while SCL is high, and SDA cannot fall: it is already low. The master's I2C peripheral sees the bus busy (BUSY on an STM32, a TWI status of 0x00 bus error on an AVR) and waits, for ever if the driver has no timeout. A power cycle of the whole board would fix it; a reset of the MCU alone does not, because the sensor did not reset.
The fix is in the I2C specification (UM10204, 3.1.16 "Bus clear"):
- Take the pins away from the I2C peripheral and drive them as open-drain GPIO outputs.
- Clock SCL up to nine times. The slave shifts out the rest of its byte with each clock; when it releases SDA (it reads high), it is waiting for an acknowledge that the master will not give, so it stops.
- Generate a STOP: SDA low, SCL high, then SDA high. Every device now sees an idle bus.
- Give the pins back to the peripheral and reset it (
SWRSTon an STM32), then set it up again.
Nine is the worst case: eight data bits and the acknowledge slot. Stop early once SDA reads high.
#include <stdio.h>
/* The levels a bus-clear routine puts on (SCL, SDA), one step per half clock: until SDA reads high, at most nine
clocks, then a STOP. sda_released_after: how many clocks the stuck device needs (it lets go after that one). */
static int bus_clear(int sda_released_after, int scl[], int sda[]) {
int n = 0, clocks = 0, sda_high = 0;
while (clocks < 9 && !sda_high) {
scl[n] = 0; sda[n] = 1; n++; /* SCL low; the master's SDA released (open drain) */
scl[n] = 1; sda[n] = 1; n++; /* SCL high: the slave shifts one bit */
clocks++;
sda_high = clocks >= sda_released_after;
}
scl[n] = 0; sda[n] = 0; n++; /* the STOP: SDA low while SCL is low */
scl[n] = 1; sda[n] = 0; n++; /* SCL high */
scl[n] = 1; sda[n] = 1; n++; /* SDA rises while SCL is high: STOP */
return clocks;
}
int main(void) {
int scl[32], sda[32];
printf("clocks needed: %d\n", bus_clear(6, scl, sda));
printf("worst case: %d\n", bus_clear(20, scl, sda));
return 0;
}
Detecting it is the other half. A driver needs a timeout on every wait (for SB, ADDR, TXE, BTF, RXNE), short enough that the main loop and the watchdog's reload carry on: a byte at 100 kHz takes 90 µs, so a few milliseconds is generous. After a timeout, read the SDA pin's input register: if it is low while nothing on the master's side drives it, a device is holding it, and the recovery runs.
Stuck pins
A pin can be stuck at a level: shorted to ground or to the supply by solder, a crushed cable, water, or a failed driver inside a device. An input then reads the same value whatever happens; an output cannot change its net and fights the short (and gets hot, and may be damaged).
Firmware cannot fix a short, but it can avoid acting on one:
- Read back outputs. After driving a relay coil or an enable line, read the pin's input register (or a feedback signal): if it does not follow, report it.
- Check inputs for plausibility. A limit switch that never changes during a move that should cross it, a tachometer input with no edges while the motor current says it turns, a "door closed" that is active during the power-on self-test when the door is open: each is a stuck-at fault.
- Design for detection. A pull-up and a pull-down tried in turn at boot show whether an input floats (open), follows (fine) or stays put (stuck). Two inputs wired as complements (normally open and normally closed contacts) detect a broken wire or short on either.
- Fail safe. Choose the level that a broken wire produces (usually the pull-up's) to mean "stop".
A stuck pin is one of the simulator's board faults: choose the pin, LOW or HIGH, and when. It holds the net whatever drives it, and warns if the firmware drives it the other way.
Clocks that drift
A crystal is specified in ppm (parts per million): ±20 ppm at 25 °C, plus its temperature curve (a 32.768 kHz watch crystal loses about 0.035 ppm/°C² away from 25 °C, so 140 ppm slow at −40 °C), plus ageing. An internal RC oscillator is far worse: ±1 % after factory trimming on an STM32's HSI, up to ±10 % on an uncalibrated one. Drift shows in three places:
| Where | Effect |
|---|---|
| Timekeeping | 20 ppm is 1.7 s a day, 10 minutes a year: a clock needs NTP, GPS or a calibrated RTC |
| UART | each end samples bits by its own clock; the error between them accumulates across the frame |
| Timeouts and protocols | CAN, LIN and USB have tight bit-timing budgets; LIN slaves resynchronise on every frame's sync byte |
The UART budget is the one firmware engineers meet first. A receiver resynchronises on the falling edge of the start bit and samples each bit in its middle. By the stop bit, the tenth of a 10-bit frame, its sampling point has moved by 9.5 bit times × the relative error. If that reaches half a bit, it samples the wrong bit: the total error between the two ends must stay below about 5 % (half a bit over 9.5), and below 2 to 3 % in practice, once sampling uncertainty and edge timing are counted. The baud-rate generator's own rounding adds to the crystal's error: at 115 200 baud from 16 MHz an STM32's divider of 138.9 rounds to 139, a 0.08 % error; an AVR at 16 MHz with U2X off cannot get within 3.5 % of 115 200, which is why many Arduino projects use 57 600 or 76 800 or a 14.7456 MHz crystal.
#include <stdio.h>
/* The baud rate a divider gives, and its error from the one wanted, in percent. */
static double baud_error(double clock_hz, double divider, double wanted) {
double actual = clock_hz / divider;
return (actual - wanted) / wanted * 100.0;
}
int main(void) {
/* An STM32 USART (BRR = clock / baud, rounded) and an AVR (UBRR = clock / 16 / baud - 1, rounded). */
printf("STM32 16 MHz, 115200: %+.2f %%\n", baud_error(16e6, 139, 115200));
printf("AVR 16 MHz, 115200: %+.2f %%\n", baud_error(16e6, 16 * (8 + 1), 115200));
printf("AVR 16 MHz, 57600: %+.2f %%\n", baud_error(16e6, 16 * (16 + 1), 57600));
/* The same AVR on an internal RC oscillator 2 % fast: the errors add. */
printf("AVR on RC +2 %%, 57600: %+.2f %%\n", baud_error(16e6 * 1.02, 16 * (16 + 1), 57600));
return 0;
}
The board fault "crystal off by" runs the chip's clock fast or slow against the world. Its timers and baud rates drift with it, and the parts on its serial lines keep their own true rates, so a mismatch garbles bytes exactly as it does on a bench.
Timeouts everywhere
What these faults share is that the firmware waits for something that does not come: an I2C flag, a UART byte, a SPI device's busy bit, a modem's reply. The rule that follows is simple and widely ignored: no loop waits without a bound. Every wait has a timeout, every timeout has a reaction (retry, recover, report, give up), and the reaction is tested by injecting the fault. A watchdog is the last line behind that rule, not a replacement for it: a watchdog reset loses the context that a timeout would have kept.
Going deeper
Interview question: How do you recover an I2C bus that a slave is holding low?
Answer: Detect it first: every wait in the driver has a timeout, and after one the firmware reads the SDA pin; low with nothing on the master's side driving it means a slave is stuck mid-byte, usually because the master reset during a transfer. Then switch SCL and SDA to open-drain GPIO outputs, clock SCL up to nine times, stopping when SDA reads high, generate a STOP by raising SDA while SCL is high, hand the pins back to the I2C peripheral and reset and re-initialise it. If the bus is still stuck, the device itself has failed: power-cycle it if the board can, or report the fault and carry on without it.
Interview question: Why does UART need the two ends' clocks to agree within a few percent, and how do you choose a baud rate and crystal?
Answer: The receiver synchronises once per frame, on the start bit's falling edge, and samples each bit in the middle of where it expects it. The relative clock error accumulates over the frame, so by the stop bit of a 10-bit frame the sample point has moved 9.5 bit times times the error; at about 5 % it lands in the wrong bit, and edge timing and sampling uncertainty leave 2 to 3 % in practice. That budget is shared by both ends' oscillators and both baud-rate generators' rounding. So compute the divider's rounding error for the clock and baud rate, use a crystal rather than an uncalibrated RC oscillator for high rates, and pick a baud rate the clock divides well (or a crystal like 14.7456 MHz that divides standard rates exactly).
Interview question: How can firmware detect that an input or output pin is stuck?
Answer: For an output, read back the pin's input register, or a feedback signal from the load, after driving it; a level that does not follow is a fault. For an input, check plausibility against other information: a sensor or switch that should change during an operation and does not, or one that is active when it cannot be. At boot, switching the internal pull-up and pull-down in turn shows whether an input floats, follows, or is held. Hardware can help: complementary contacts, a test pulse on a safety input, or a feedback resistor network. The firmware then fails safe, choosing the meaning of a broken wire so that it stops the machine.
Explain it: In your own words, explain why resetting the MCU does not free an I2C bus that a sensor is holding low, and what does.
Answer: The sensor's state machine is separate from the MCU and has no reset input on the bus. It was in the middle of sending a byte when the master stopped clocking, and it holds SDA low while it waits for the next clock. Resetting the MCU only restarts the master; the sensor still waits, so the bus never looks idle and no START can be made. What frees it is giving the sensor the clocks it is waiting for: up to nine pulses on SCL, made with the pins as GPIO, let it finish the byte and release SDA, and a STOP then returns it, and every other device, to idle.