Topics / Communication Protocols / Q16
How do you recover a stuck I2C bus?
Short answer: If a target was reset or interrupted in the middle of a read, it may still be holding SDA low, waiting to send the rest of a byte; the controller then cannot generate a START. To recover: switch SCL to GPIO open-drain mode, toggle SCL up to 9 times until the target releases SDA (it finishes its byte and sees a NACK because SDA is high on the 9th clock), generate a STOP condition manually, then return the pins to I2C mode and reset the I2C peripheral.
#include <stdbool.h>
void scl_set(int level); void sda_set(int level); int sda_get(void); void delay_us(unsigned us);
bool i2c_bus_recover(void) /* pins temporarily configured as open-drain GPIO */
{
sda_set(1);
for (int i = 0; i < 9 && !sda_get(); i++) {
scl_set(0); delay_us(5);
scl_set(1); delay_us(5);
}
if (!sda_get()) return false; /* still stuck: power-cycle the device if possible */
sda_set(0); delay_us(5); /* generate STOP: SDA low → high while SCL high */
scl_set(1); delay_us(5);
sda_set(1); delay_us(5);
return true; /* now re-init the I2C peripheral */
}
Other causes of a stuck bus
- SCL held low by a crashed target (clock stretching forever): clocking does not help; reset or power-cycle the device (a GPIO-controlled reset line or power switch on the board is good design practice).
- Controller peripheral in a bad state after a glitch: reset the peripheral (many MCUs have errata requiring this).
- Missing or wrong pull-ups, shorted lines, or a device powered off that clamps the lines through its protection diodes.
Prevention: use timeouts on every I2C wait, call bus recovery on timeout, and design hardware so devices can be reset. The Linux kernel provides i2c_recover_bus() with GPIO-based recovery described in the device tree (scl-gpios, sda-gpios).