Simvik

Retries, backoff and bus recovery

Decide which bus errors to retry, how long to wait, and when to recover a stuck bus. A hard embedded C problem (Driver design: HAL versus bare metal), run…

hard · Driver design: HAL versus bare metal · driver · i2c · error-handling · retry

Write sensor_write_reg(reg, val): send the two bytes reg, val to the device at SENSOR_ADDR with bus_xfer, and handle failures by type. Make at most MAX_ATTEMPTS transfers per call, numbered 1, 2, 3:

  • BUS_OK: return BUS_OK.
  • BUS_NACK (the device is busy, for example finishing an EEPROM write) or BUS_ARB_LOST (another controller won the bus): these pass, so if attempts remain, delay_ms(1 << (k - 1)) after failed attempt k (1 ms, then 2 ms) and try again.
  • BUS_STUCK (a slave is holding SDA low): call bus_recover() and try again at once, but only the first time it happens in a call. A second BUS_STUCK is returned.
  • Anything else, such as BUS_BAD_ARG: a bug, not bad luck. Return it at once.

When the attempts run out, return the last error.

Starter code

int sensor_write_reg(uint8_t reg, uint8_t val) {
  uint8_t tx[2] = { reg, val };
  int rc = BUS_OK;
  for (int k = 1; k <= MAX_ATTEMPTS; k++) {
    rc = bus_xfer(SENSOR_ADDR, tx, 2);
    if (rc == BUS_OK) break;
  }
  return rc;
}

Example tests

A busy device answers on the third try

int r[] = { BUS_NACK, BUS_NACK, BUS_OK };
attempt(r, 3);

Expected output:

xfer:NACK wait:1 xfer:NACK wait:2 xfer:OK => 0

A stuck bus is recovered

int r[] = { BUS_STUCK, BUS_OK };
attempt(r, 2);

Expected output:

xfer:STUCK recover xfer:OK => 0

Learn it first

More Driver design: HAL versus bare metal problems