Simvik

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:

  1. If SDA is already high, the bus is free: return true without clocking.
  2. Otherwise pulse SCL (low, then high, a few microseconds each) until SDA reads high, at most 9 times: a byte plus its ACK bit.
  3. Once SDA is high, send a STOP: SCL low, SDA low, SCL high, then SDA high.
  4. 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 ok

A 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 clocks

Learn it first

  • I2C · Addressing, repeated start, clock stretching and bus recovery.

More I2C problems