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: returnBUS_OK.BUS_NACK(the device is busy, for example finishing an EEPROM write) orBUS_ARB_LOST(another controller won the bus): these pass, so if attempts remain,delay_ms(1 << (k - 1))after failed attemptk(1 ms, then 2 ms) and try again.BUS_STUCK(a slave is holding SDA low): callbus_recover()and try again at once, but only the first time it happens in a call. A secondBUS_STUCKis 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 => 0A stuck bus is recovered
int r[] = { BUS_STUCK, BUS_OK };
attempt(r, 2);Expected output:
xfer:STUCK recover xfer:OK => 0Learn it first
- Driver design: HAL versus bare metal · Layering a driver so it is testable, portable and still fast.
More Driver design: HAL versus bare metal problems
- One interface, two sensors · Put two temperature sensor drivers behind one ops table so the application does not care which chip is fitted.
- A non-blocking driver · Start a conversion and poll for it, with a timeout, instead of waiting in a loop.
- A driver and its interface: led.h and led.c · Split an LED driver into the header the application includes and the source file that keeps the register work to itself.