Recover a stuck bus
Clock a stuck device out with up to nine pulses, then send a STOP. A medium embedded C problem (I2C), run and graded in the browser.
medium · I2C · i2c · recovery · gpio
If the microcontroller resets in the middle of an I2C read, the device it was talking to may still be sending a byte, and it holds SDA low forever, waiting for clocks that never come. Every later transfer fails. The standard recovery, done with the pins as plain GPIO:
- If SDA is already high, the bus is free: return true without clocking.
- Otherwise pulse SCL (low, then high, a few microseconds each) until SDA reads high, at most 9 times: a byte plus its ACK bit.
- Once SDA is high, send a STOP: SCL low, SDA low, SCL high, then SDA high.
- Return whether SDA is high at the end. If it is still low after 9 pulses, give up and return false.
Starter code
bool i2c_recover(void) {
sda_set(false); // just send a STOP
scl_set(true);
sda_set(true);
return sda_read();
}Example tests
A device stuck three bits into its byte
bus(3);
report(i2c_recover());Expected output:
result 1, stop 1, SDA high, pulses okA free bus needs no clocks
bus(0);
bool r = i2c_recover();
printf("result %d, %s\n", r, pulses == 0 ? "no clocks" : "clocked");Expected output:
result 1, no clocksLearn it first
- I2C · Addressing, repeated start, clock stretching and bus recovery.
More I2C problems
- Scan the bus · Find every device on the bus without probing the reserved addresses.
- Read a 16-bit register · Write the register pointer, read two bytes back with a repeated start, and handle a NACK.
- Size the pull-up resistors · Work out the smallest and largest pull-up that meet the I2C specification.
- Driver: write an EEPROM over I2C, with ACK polling · Send an I2C write with the hardware's byte-by-byte handshake, then poll until the EEPROM finishes writing.
- Driver: read registers with a repeated start · Write a register address, then read bytes back without releasing the bus in between.
- Fix: every second transfer is cut short · A write routine leaves STOPF set, so the next transfer thinks it has already finished.
- HVAC controller: trust the humidity reading · Combine the bytes an I²C humidity sensor returns, check their CRC, and scale them.