Simvik

The bus recovery sequence

Clock SCL until a stuck slave lets go of SDA, at most nine times, then make a STOP. A medium embedded C problem (Stuck buses, stuck pins and drifting…

medium · Stuck buses, stuck pins and drifting clocks · i2c · recovery · gpio

A slave stopped in the middle of a byte holds SDA low. Write bus_clear(), which drives the pins as GPIO through three functions written for you:

  • scl(level) and sda(level) set a pin (1 releases it, open drain; 0 pulls it low),
  • sda_read() reads SDA.

SCL and SDA start high (released). While sda_read() is 0, give one clock (scl(0) then scl(1)), at most 9 times. If SDA is then released, make a STOP: scl(0), sda(0), scl(1), sda(1), and return the number of clocks given (0 if SDA was already high). If SDA is still low after 9 clocks the device has failed: return -1 without a STOP.

The test's bus prints ^ for each clock the slave sees and STOP for a stop.

Starter code

int bus_clear(void) {
  for (int i = 0; i < 9; i++) {
    scl(0);
    scl(1);
  }
  scl(0);
  sda(0);
  scl(1);
  sda(1);
  return 9;
}

Example tests

A slave that lets go after six clocks

run(6);

Expected output:

^^^^^^ STOP -> 6

A bus that was not stuck

run(0);

Expected output:

 STOP -> 0

Learn it first

More Stuck buses, stuck pins and drifting clocks problems

  • Will this link work? · Add up both ends' clock errors on a UART and compare them with the frame's budget.