
An I2C bus that refuses to start — SDA stuck low and the controller reporting a busy bus on the first transfer after reset — is a classic field failure. The root cause is almost always a target (slave) device left mid-transaction by a controller reset, power glitch, or bus noise, though frozen clock stretching and hardware faults can also lock the bus. This guide covers the complete 9-clock recovery sequence, how to distinguish legitimate clock stretching from a stuck bus, SMBus timeout interactions, multi-master recovery coordination, and the board-level hardware provisions required for reliable field recovery.
The symptom is consistent across MCU families: after a watchdog reset, brownout, or debugger halt, the first HAL_I2C_Master_Transmit() or I2C_MasterTransfer() call returns HAL_BUSY (for example, when STM32Cube HAL waits I2C_TIMEOUT_BUSY, typically 25 ms, for I2C_FLAG_BUSY to clear) or a driver timeout error. Probing the bus with a logic analyzer or oscilloscope shows SDA held near 0 V indefinitely while SCL sits idle at VDD (3.3 V). No START condition can be generated because the controller cannot pull SDA from high to low when SDA is already low.
I2C1: HAL_BUSY / bus-busy timeout on first transfer after controller resetSDA: 0.0 V (held low by target)SCL: 3.3 V (released high by pull-up)
This is not clock stretching: the target is not holding SCL low to ask for processing time. Instead, the target device is actively pulling SDA low because its internal I2C state machine believes a transfer is still in progress and is waiting for the next SCL edge.
A target device enters a stuck-bus state through four main mechanisms:
SDA low — most commonly during a read transfer (when the target is shifting out a 0 data bit, such as an EEPROM sequential read) or right on the 9th-clock ACK slot of a write transfer. After reboot, the controller’s I2C peripheral sees SDA low (BUSY set) and never issues the remaining clocks.SCL/SDA violate glitch-filter margins and create false START, clock, or address-match conditions, desynchronizing the target’s bit counter from the controller so it lands in a transmit or ACK state holding SDA low.NOSTRETCH = 0), an interrupt handler that returns without servicing ADDR, RXNE, or TXDR leaves the peripheral hardware holding SCL low indefinitely.NXP’s I2C-bus specification (UM10204 Rev. 7.0, Section 3.1.16 “Bus clear”) states that when SDA is stuck low, the controller should send nine clock pulses so the device holding the bus releases it; if SCL is stuck low (or SDA does not release within nine clocks), the controller must assert a hardware reset or cycle power. Practical controller recovery implementations (such as TI SCPA069 and Linux i2c_generic_scl_recovery()) follow the clock pulses with a manufactured STOP condition to reset all target state machines to idle. Before running recovery, however, you must distinguish a slow target from a stuck one.
| Condition | SDA State | SCL State | Controller Action |
|---|---|---|---|
| Legitimate clock stretch | Any (last driven bit or high) | Held low by target | Wait up to slave max stretch timeout |
| Stuck bus (SDA low) | Held low by target | Released (high) | Run 9-clock recovery + STOP |
| Stuck bus (SCL low) | Any | Held low beyond max stretch | Hardware reset or power cycle required |
Clock stretching only holds SCL low (note that SDA may legitimately sit at 0 or 1 during a stretch if the target stretches immediately after driving a 0 data bit or ACK before the next SCL falling edge). Conversely, if SCL is high while the bus should be idle and SDA is low, the bus cannot be clock stretching — a target is stuck holding SDA low.
Each I2C frame unit consists of 8 data bits plus 1 ACK/NACK bit (9 clock cycles total). In the worst case, a target interrupted right at bit 7 of a read byte needs 8 clocks to finish the byte plus 1 clock for the ACK/NACK slot. Because the controller leaves SDA released high (1) while pulsing SCL, the 9th clock acts as a NACK to any transmitting target, which per I2C protocol must immediately release SDA so the controller can issue a STOP condition. Polling SDA after each rising edge and exiting early as soon as SDA returns high is equally critical: if a target was only stuck finishing an ACK slot from an interrupted write, stopping after 1 clock prevents accidentally clocking 0xFF bytes into the device.
Software recovery must manipulate SCL and SDA directly in open-drain GPIO mode (GPIO_MODE_OUTPUT_OD). Never attempt to recover with the hardware I2C peripheral enabled, because the peripheral’s own bus-busy arbiter blocks START/STOP generation whenever SDA is low. Also preload both GPIO output latches high (GPIO_PIN_SET) before switching the pin mode from alternate function to GPIO output so the MCU itself never injects a spurious low glitch onto the bus.
#include <stdbool.h>#include <stdint.h>#define I2C_RECOVER_HALF_PERIOD_US 5U /* 100 kHz Standard-mode baseline */#define I2C_STRETCH_TIMEOUT_US 5000U /* 5 ms max wait per recovery edge */typedef enum {I2C_RECOVER_OK = 0,I2C_RECOVER_ERR_SCL_STUCK_LOW,I2C_RECOVER_ERR_STRETCH_TIMEOUT,I2C_RECOVER_ERR_SDA_STUCK_LOW} i2c_recover_status_t;typedef struct {I2C_HandleTypeDef *hi2c;GPIO_TypeDef *scl_port;uint16_t scl_pin;GPIO_TypeDef *sda_port;uint16_t sda_pin;uint32_t scl_af;uint32_t sda_af;} i2c_bus_cfg_t;/* Implemented below using DWT->CYCCNT (or TIMx->CNT on Cortex-M0/M0+) */static void i2c_delay_us(uint32_t delay_us);static bool i2c_wait_scl_high_us(const i2c_bus_cfg_t *cfg, uint32_t timeout_us){uint32_t elapsed = 0U;while (HAL_GPIO_ReadPin(cfg->scl_port, cfg->scl_pin) != GPIO_PIN_SET) {if (elapsed >= timeout_us) {return false;}i2c_delay_us(1U);elapsed++;}return true;}static void i2c_pins_to_gpio_od(const i2c_bus_cfg_t *cfg){GPIO_InitTypeDef gpio = {0};/* Preload ODR=1 before switching MODER so pins never glitch low */HAL_GPIO_WritePin(cfg->scl_port, cfg->scl_pin, GPIO_PIN_SET);HAL_GPIO_WritePin(cfg->sda_port, cfg->sda_pin, GPIO_PIN_SET);gpio.Mode = GPIO_MODE_OUTPUT_OD;gpio.Pull = GPIO_NOPULL; /* External bus pull-ups govern rise time */gpio.Speed = GPIO_SPEED_FREQ_HIGH;gpio.Pin = cfg->scl_pin;HAL_GPIO_Init(cfg->scl_port, &gpio);gpio.Pin = cfg->sda_pin;HAL_GPIO_Init(cfg->sda_port, &gpio);}static void i2c_pins_restore_af(const i2c_bus_cfg_t *cfg){GPIO_InitTypeDef gpio = {0};gpio.Mode = GPIO_MODE_AF_OD;gpio.Pull = GPIO_NOPULL;gpio.Speed = GPIO_SPEED_FREQ_HIGH;gpio.Pin = cfg->scl_pin;gpio.Alternate = cfg->scl_af;HAL_GPIO_Init(cfg->scl_port, &gpio);gpio.Pin = cfg->sda_pin;gpio.Alternate = cfg->sda_af;HAL_GPIO_Init(cfg->sda_port, &gpio);}i2c_recover_status_t i2c_bus_recover(const i2c_bus_cfg_t *cfg){i2c_recover_status_t status = I2C_RECOVER_OK;bool was_initialized = (cfg->hi2c != NULL) &&(HAL_I2C_GetState(cfg->hi2c) != HAL_I2C_STATE_RESET);/* Prerequisite: GPIO port clocks enabled. If already initialized, disable I2C* before taking GPIO control (and back up TIMEOUTR on I2C v2 if customized). */if (was_initialized) {HAL_I2C_DeInit(cfg->hi2c);}i2c_pins_to_gpio_od(cfg);i2c_delay_us(10U); /* Allow external pull-ups to settle *//* Fast path: both lines already idle high */if ((HAL_GPIO_ReadPin(cfg->sda_port, cfg->sda_pin) == GPIO_PIN_SET) &&(HAL_GPIO_ReadPin(cfg->scl_port, cfg->scl_pin) == GPIO_PIN_SET)) {goto restore_peripheral;}/* If SCL itself will not rise, clock line is held low (stretch or HW fault) */if (!i2c_wait_scl_high_us(cfg, I2C_STRETCH_TIMEOUT_US)) {status = I2C_RECOVER_ERR_SCL_STUCK_LOW;goto restore_peripheral;}/* Drive up to 9 clock cycles on SCL with SDA released high */for (uint8_t i = 0U; i < 9U; i++) {if (HAL_GPIO_ReadPin(cfg->sda_port, cfg->sda_pin) == GPIO_PIN_SET) {break; /* Target released SDA */}/* SCL low phase (t_LOW >= 4.7 us) */HAL_GPIO_WritePin(cfg->scl_port, cfg->scl_pin, GPIO_PIN_RESET);i2c_delay_us(I2C_RECOVER_HALF_PERIOD_US);/* Release SCL and wait for pull-up rise / any brief stretch BEFORE t_HIGH */HAL_GPIO_WritePin(cfg->scl_port, cfg->scl_pin, GPIO_PIN_SET);if (!i2c_wait_scl_high_us(cfg, I2C_STRETCH_TIMEOUT_US)) {status = I2C_RECOVER_ERR_STRETCH_TIMEOUT;goto restore_peripheral;}i2c_delay_us(I2C_RECOVER_HALF_PERIOD_US); /* t_HIGH >= 4.0 us */}/* Verify SDA released before attempting STOP */if (HAL_GPIO_ReadPin(cfg->sda_port, cfg->sda_pin) != GPIO_PIN_SET) {status = I2C_RECOVER_ERR_SDA_STUCK_LOW;goto restore_peripheral;}/* Manufacture STOP condition: SDA low-to-high while SCL is high */HAL_GPIO_WritePin(cfg->scl_port, cfg->scl_pin, GPIO_PIN_RESET);i2c_delay_us(I2C_RECOVER_HALF_PERIOD_US);HAL_GPIO_WritePin(cfg->sda_port, cfg->sda_pin, GPIO_PIN_RESET);i2c_delay_us(I2C_RECOVER_HALF_PERIOD_US);HAL_GPIO_WritePin(cfg->scl_port, cfg->scl_pin, GPIO_PIN_SET);if (!i2c_wait_scl_high_us(cfg, I2C_STRETCH_TIMEOUT_US)) {status = I2C_RECOVER_ERR_STRETCH_TIMEOUT;goto restore_peripheral;}i2c_delay_us(I2C_RECOVER_HALF_PERIOD_US); /* t_SU;STO >= 4.0 us */HAL_GPIO_WritePin(cfg->sda_port, cfg->sda_pin, GPIO_PIN_SET);i2c_delay_us(I2C_RECOVER_HALF_PERIOD_US); /* t_BUF >= 4.7 us */if ((HAL_GPIO_ReadPin(cfg->sda_port, cfg->sda_pin) != GPIO_PIN_SET) ||(HAL_GPIO_ReadPin(cfg->scl_port, cfg->scl_pin) != GPIO_PIN_SET)) {status = I2C_RECOVER_ERR_SDA_STUCK_LOW;}restore_peripheral:i2c_pins_restore_af(cfg);if (was_initialized) {(void)HAL_I2C_Init(cfg->hi2c);}return status;}
Note why i2c_bus_recover() uses microsecond busy-wait delays rather than HAL_Delay(1): if recovery is triggered from an error callback or ISR where SysTick cannot preempt, HAL_Delay() spins forever. Microsecond delays also keep the entire 9-clock recovery sequence near ~110 us rather than tens of milliseconds.
The recovery clock rate must stay within the slowest target’s specification. Standard-mode (<= 100 kHz) timing from NXP UM10204 Table 10 is the safest universal baseline:
Standard-mode (<= 100 kHz) minimum timing requirements (UM10204 Table 10):- t_LOW (SCL low period) >= 4.7 us- t_HIGH (SCL high period) >= 4.0 us- t_SU;STO (STOP condition setup) >= 4.0 us- t_BUF (bus free STOP to START) >= 4.7 us- t_r (max SDA/SCL rise time) <= 1000 ns (C_b <= 400 pF)Using 5 us half-periods (5 us low + 5 us high = 10 us period = 100 kHz max):- Satisfies t_LOW >= 4.7 us, t_HIGH >= 4.0 us, t_SU;STO >= 4.0 us, t_BUF >= 4.7 us.- Polling SCL == HIGH before counting t_HIGH automatically absorbs bus rise time t_r.
When implementing i2c_delay_us() with ARM Cortex-M3/M4/M7/M33 Data Watchpoint and Trace (DWT->CYCCNT), remember two hardware prerequisites: DWT->CYCCNT is disabled at reset until software unlocks TRCENA and CYCCNTENA, and Cortex-M0/M0+ cores (STM32F0/G0/L0) do not implement DWT->CYCCNT and must use a hardware timer (TIMx->CNT) instead.
static void i2c_dwt_init(void){CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;DWT->CYCCNT = 0U;DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;}static void i2c_delay_us(uint32_t delay_us){uint32_t start = DWT->CYCCNT;/* Ceiling division prevents under-timing when SystemCoreClock is non-integer MHz */uint32_t ticks = (uint32_t)(((uint64_t)SystemCoreClock * delay_us + 999999ULL) / 1000000ULL);while ((DWT->CYCCNT - start) < ticks) {__NOP();}}
The SMBus specification (Version 3.2) adds mandatory clock-low timeouts that do not exist in standard I2C:
SMBus 3.2 timeout limits:- T_TIMEOUT (clock low timeout, min to max) = 25 ms to 35 ms- T_LOW:SEXT (cumulative target extend per msg) <= 25 ms- T_LOW:MEXT (cumulative controller extend/byte) <= 10 ms
If SMBCLK (SCL) stays low longer than T_TIMEOUT (25 ms min, 35 ms max), SMBus devices reset their bus interfaces and become ready for a new START. While a ~110 us 9-clock recovery sequence only holds SCL low for 5 us per pulse (far below 25 ms), mixing slow clock-stretching I2C targets with SMBus devices creates a trap: an I2C ADC or sensor stretching SCL past 25 ms causes co-resident SMBus devices to self-reset mid-transaction.
On STM32 I2C v2 peripherals (F0, F3, F7, G0, G4, H7, L0, L4, U5), hardware SMBus timeout detection lives in I2Cx->TIMEOUTR. Note ST’s exact CMSIS bit macro spelling I2C_TIMEOUTR_TIMOUTEN (omitting the second E in TIMEOUT) and I2C_TIMEOUTR_TEXTEN. Older STM32 I2C v1 peripherals (F1, F2, F4) do not have a TIMEOUTR register.
/* Disable hardware SMBus timeouts on STM32 I2C v2 for pure I2C buses with long stretches.* Per RM0433, TIMEOUTA/TIMEOUTB/TIDLE may only be changed when TIMOUTEN == 0 and TEXTEN == 0. */I2Cx->TIMEOUTR &= ~(I2C_TIMEOUTR_TIMOUTEN | I2C_TIMEOUTR_TEXTEN);
+-------------------------------------------------------------------------+| I2C BUS RECOVERY FLOW |+-------------------------------------------------------------------------+| || START: Bus busy / HAL_BUSY on transfer || | || v || +-----------------------------+ || | DeInit I2C, preload ODR=1, | || | switch SCL/SDA to GPIO_OD | || +-----------------------------+ || | || v || +-----------------------------+ YES +---------------------------+ || | SDA == 1 AND SCL == 1? +-------->| Bus already idle | || +-----------------------------+ | Restore AF, return OK | || | NO +---------------------------+ || v || +-----------------------------+ NO +---------------------------+ || | Wait SCL == 1 (stretch tmo) +-------->| SCL stuck low | || +-----------------------------+ | Return ERR_SCL_STUCK_LOW | || | YES +---------------------------+ || v || +-------------------------------------------------------------------+ || | FOR i = 0 .. 8 (up to 9 SCL clock cycles, SDA released high): | || | 1. If SDA == 1 -> BREAK (target released SDA) | || | 2. Drive SCL = 0, delay 5 us (t_LOW >= 4.7 us) | || | 3. Release SCL = 1, wait SCL == 1 (else ERR_STRETCH_TIMEOUT) | || | 4. Delay 5 us (t_HIGH >= 4.0 us) | || +-------------------------------------------------------------------+ || | || v || +-----------------------------+ NO +---------------------------+ || | SDA == 1 after 9 clocks? +-------->| Target still driving SDA | || +-----------------------------+ | Return ERR_SDA_STUCK_LOW | || | YES | (HW reset / power cycle) | || v +---------------------------+ || +-----------------------------+ || | Generate STOP: | || | SCL=0 -> SDA=0 -> SCL=1 -> | || | wait t_SU;STO -> SDA=1 | || +-----------------------------+ || | || v || +-----------------------------+ YES +---------------------------+ || | Verify SDA == 1 AND SCL == 1+-------->| Restore AF, Re-init I2C | || +-----------------------------+ | Return RECOVER_OK | || | NO +---------------------------+ || v || Return ERR_SDA_STUCK_LOW || |+-------------------------------------------------------------------------+
The hardest field decision is distinguishing a slow target (EEPROM internal write cycle, sensor ADC conversion) from a stuck one. Standard I2C (UM10204) imposes no maximum timeout on clock stretching — a compliant target can legally hold SCL low for tens or hundreds of milliseconds.
Size your stretch timeout from the datasheet worst-case stretch time of every device on that bus segment (for example, SHT3x measurement hold vs. AT24C256 EEPROM polling) plus margin, and keep the watchdog fed during long waits. When waiting in thread context, HAL_GetTick() is simple (note that inside an ISR at equal or higher priority than SysTick, HAL_GetTick() does not advance, so use a hardware timer or DWT->CYCCNT instead).
#define I2C_LEGITIMATE_STRETCH_MAX_MS 50U /* Adjust to slowest device on bus */static bool i2c_wait_for_slave_ready_ms(const i2c_bus_cfg_t *cfg, uint32_t timeout_ms){uint32_t start = HAL_GetTick();while ((uint32_t)(HAL_GetTick() - start) < timeout_ms) {if (HAL_GPIO_ReadPin(cfg->scl_port, cfg->scl_pin) == GPIO_PIN_SET) {return true; /* Target released SCL */}/* Optional: feed watchdog or yield RTOS task here */}return false; /* Timeout exceeded -- treat SCL as stuck */}
Rule of thumb: Never pick an arbitrary 50 ms timeout without checking every target datasheet. If a sensor or ADC legitimately stretches SCL for 200 ms, a 50 ms timeout falsely aborts healthy transfers and leaves the target mid-conversion.
+-------------------------------------------------------------------------+| IS THE BUS STUCK OR STRETCHING? |+-------------------------------------------------------------------------+| || Sample SCL and SDA (scope / logic analyzer / GPIO read when bus idle) || | || v || +--------------------------+ YES +------------------------------+ || | Is SCL == 0? +-------->| CLOCK STRETCHING OR SCL STUCK| || +--------------------------+ | Wait up to max stretch spec | || | NO (SCL == 1) | If still low after timeout: | || v | HW RESET or power cycle | || +--------------------------+ YES +------------------------------+ || | Is SDA == 0? +-------->| STUCK BUS (SDA HELD LOW) | || +--------------------------+ | Run 9-clock recovery + STOP | || | NO (SDA == 1) | If still low: HW reset/POR | || v +------------------------------+ || BUS IDLE (SCL == 1, SDA == 1) || |+-------------------------------------------------------------------------+
I_OL (3 mA in Standard/Fast mode) and raise V_OL above 0.4 V. Size R_p using NXP UM10204 Section 7.1 and TI SLVA689:Pull-up resistor bounds (NXP UM10204 Section 7.1 / TI SLVA689):Minimum pull-up resistance (logic-low sink limit, I_OL = 3 mA, V_OL(max) = 0.4 V):R_p(min) = (VDD - V_OL(max)) / I_OLAt VDD = 3.3 V: (3.3 - 0.4) / 0.003 A = 967 OhmAt VDD = 5.0 V: (5.0 - 0.4) / 0.003 A = 1.53 kOhm (1 kOhm violates I_OL at 5 V!)Maximum pull-up resistance (rise-time limit t_r from 0.3*VDD to 0.7*VDD):R_p(max) = t_r / (0.8473 * C_b)At 100 kHz (t_r <= 1000 ns), C_b = 200 pF: 1000e-9 / (0.8473 * 200e-12) = 5.90 kOhmAt 400 kHz (t_r <= 300 ns), C_b = 200 pF: 300e-9 / (0.8473 * 200e-12) = 1.77 kOhm
SDA low, but an active I2C host adapter/emulator or an unpowered debug header/target attached to the bus can clamp SDA/SCL through ESD protection diodes. Disconnect auxiliary probes and powered-off sub-boards when isolating a fault.C_b near or past the 400 pF limit. Segment capacitance with an I2C bus repeater such as the TI TCA9517 (keeping in mind that its B-side enforces a ~0.52 V typical static voltage offset and cannot be connected directly to another static-offset B-side buffer).In a multi-master (multi-controller) system, only one controller may drive bit-banged recovery at a time. Hardware I2C arbitration only operates during valid START/address/data frames inside the I2C peripheral; if two controllers toggle SCL asynchronously in GPIO mode, their wired-AND clock pulses collide into narrow runt pulses that violate t_LOW/t_HIGH or double-clock targets past the 9-clock boundary.
Do not try to implement a mutex by having two controllers poll and pull a single shared open-drain GPIO line: checking “pin high” and then driving “pin low” is a classic check-then-act (TOCTOU) race where both controllers can read high simultaneously and both believe they own the bus. Instead, use either:
SCL; if they detect a stuck bus, they assert an active-low RECOVERY_REQ# line (or wait for bus idle) and let the primary execute recovery.REQ_OUT and PEER_REQ_IN GPIOs with asymmetric tie-breaking (master A yields to master B if both request simultaneously) before touching SCL/SDA.static bool i2c_wait_bus_idle_us(const i2c_bus_cfg_t *cfg, uint32_t quiet_us, uint32_t timeout_us);/* Multi-master recovery coordination with designated primary owner + open-drain request line */i2c_recover_status_t i2c_multi_master_recover(const i2c_bus_cfg_t *cfg, bool is_primary_owner){if (!is_primary_owner) {/* Assert active-low open-drain request pulse (triggers primary EXTI), then wait for idle */HAL_GPIO_WritePin(RECOVERY_REQ_PORT, RECOVERY_REQ_PIN, GPIO_PIN_RESET);i2c_delay_us(200U);HAL_GPIO_WritePin(RECOVERY_REQ_PORT, RECOVERY_REQ_PIN, GPIO_PIN_SET);return i2c_wait_bus_idle_us(cfg, 100U, 5000U) ? I2C_RECOVER_OK : I2C_RECOVER_ERR_SDA_STUCK_LOW;}/* Primary invokes recovery only after BUSY persists past max transaction/stretch window */return i2c_bus_recover(cfg);}
For normal hardware transactions, NXP UM10204 Section 3.1.8 specifies that a controller losing wired-AND arbitration on SDA immediately shuts off its SDA output stage, may continue generating SCL pulses only until the end of the byte in which arbitration was lost, switches to target mode if addressed, and waits for a STOP condition before retrying.
During bit-banged recovery, if the primary controller detects unexpected SCL contention (for instance, SCL remains low past I2C_STRETCH_TIMEOUT_US or SDA fails to stay high during STOP generation), it must immediately release both SCL and SDA high, restore AF_OD pins, wait for continuous bus idle, and avoid retrying without backoff. Keeping the recovery sequence short (~110 us at 100 kHz) minimizes any collision window.
After recovery completes, all controllers must verify that the bus remains continuously idle (SDA == 1 and SCL == 1) for at least t_BUF (4.7 us min at 100 kHz, 1.3 us min at 400 kHz) before attempting a START. A blind 100 us sleep does not detect whether a peer controller started a transfer halfway through the sleep; instead, reset the idle timer whenever either line drops low:
/* Wait until BOTH SDA and SCL stay continuously high for quiet_us (must exceed t_BUF) */static bool i2c_wait_bus_idle_us(const i2c_bus_cfg_t *cfg, uint32_t quiet_us, uint32_t timeout_us){uint32_t idle_elapsed = 0U;uint32_t total_elapsed = 0U;while (total_elapsed < timeout_us) {if ((HAL_GPIO_ReadPin(cfg->sda_port, cfg->sda_pin) == GPIO_PIN_SET) &&(HAL_GPIO_ReadPin(cfg->scl_port, cfg->scl_pin) == GPIO_PIN_SET)) {idle_elapsed++;if (idle_elapsed >= quiet_us) {return true;}} else {idle_elapsed = 0U; /* Bus activity observed; restart quiet window */}i2c_delay_us(1U);total_elapsed++;}return false;}
Software recovery fails when SCL is locked low, an internal latch-up holds SDA low across 9+ clocks, or a transceiver fails. Production boards that must recover in the field without full system power loss need explicit hardware recovery paths.
| Feature | Purpose | Correct Implementation |
|---|---|---|
| High-side load switch | Power-cycle an individual target or branch | Integrated high-side switch (TI TPS22918 with QOD) or high-side P-MOSFET (Si2301, AO3401); never cut GND with a low-side N-MOSFET |
Hardware RESET line | Reset targets without cutting power | Active-low open-drain RESET# pulled up to VDD, driven by controller GPIO |
| Isolated bus switch | Isolate stuck segments from healthy devices | TI TCA9548A 8-channel I2C switch with /RESET pin |
| Galvanic I2C isolator | Break ground loops and contain electrical faults | TI ISO1540 (bidirectional SDA + SCL, supports clock stretching and multi-master); use ISO1541 only for single-master, non-stretching buses |
| Analog bus monitor | Diagnose elevated V_OL, weak pull-ups, or contention | High-impedance ADC tap on SDA/SCL (keep sampling C_in within C_b budget) |
Avoid two common hardware traps:
Si2302) leaves VCC connected while SDA/SCL pull-ups seek ground through ESD diodes, causing latch-up and ground-offset failures. Always switch the high side (VCC).VCC load switch while SDA/SCL pull-ups remain powered at 3.3 V, current flows through the target’s internal upper ESD clamp diodes and holds its internal rail around ~2.6 V, preventing POR! Either power the segment’s pull-ups from the switched rail, isolate the segment behind a TCA9548A switch (RESET# low), or actively hold SDA/SCL low during the power-off interval.An I2C switch such as the TCA9548A isolates downstream channels behind pass FETs. Notice a critical trap: if a currently selected downstream channel gets stuck holding SDA low, I2C writes to the TCA9548A itself will fail because the pass FET connects the stuck downstream line straight to the upstream bus! You must pulse the TCA9548A active-low /RESET pin (t_W(L) >= 6 ns per datasheet; e.g., 1 us in GPIO) first to deselect all channels and free the upstream bus before selecting healthy channels:
/* Pulse TCA9548A active-low RESET pin (t_W(L) >= 6 ns) to isolate a stuck downstream channel */void tca9548a_hardware_reset(GPIO_TypeDef *rst_port, uint16_t rst_pin){HAL_GPIO_WritePin(rst_port, rst_pin, GPIO_PIN_RESET);i2c_delay_us(1U);HAL_GPIO_WritePin(rst_port, rst_pin, GPIO_PIN_SET);i2c_delay_us(1U); /* t_REC(STA) = 0 ns min */}/* Select TCA9548A channel (0..7) safely; reset mux if upstream bus is stuck */bool tca9548a_select_channel(I2C_HandleTypeDef *hi2c, const i2c_bus_cfg_t *cfg, uint8_t channel){if (channel >= 8U) {return false;}uint8_t cmd = (uint8_t)(1U << channel);if (HAL_I2C_Master_Transmit(hi2c, (uint16_t)(TCA9548A_ADDR << 1), &cmd, 1U, 10U) != HAL_OK) {/* Active downstream branch may be dragging upstream low: isolate all channels first */tca9548a_hardware_reset(TCA_RST_PORT, TCA_RST_PIN);return false;}return i2c_wait_bus_idle_us(cfg, 20U, 1000U);}
Resetting the TCA9548A rescues the rest of the system immediately, though the faulty channel remains stuck until you re-select only that channel to run 9-clock recovery or cycle its downstream load switch.
i2c_recover_status_t i2c_hardware_recover(const i2c_bus_cfg_t *cfg, uint8_t slave_index){/* 1. Try non-destructive 9-clock software recovery first */if (i2c_bus_recover(cfg) == I2C_RECOVER_OK) {return I2C_RECOVER_OK;}bool was_initialized = (cfg->hi2c != NULL) &&(HAL_I2C_GetState(cfg->hi2c) != HAL_I2C_STATE_RESET);/* 2. Prevent phantom powering through SDA/SCL pull-ups while rail is off */if (was_initialized) {HAL_I2C_DeInit(cfg->hi2c);}i2c_pins_to_gpio_od(cfg);HAL_GPIO_WritePin(cfg->sda_port, cfg->sda_pin, GPIO_PIN_RESET);HAL_GPIO_WritePin(cfg->scl_port, cfg->scl_pin, GPIO_PIN_RESET);/* 3. Disable high-side load switch (with Quick Output Discharge, e.g., TPS22918) */load_switch_disable(slave_index);HAL_Delay(100U); /* Allow bulk capacitors to discharge below POR threshold *//* 4. Release bus lines high, then re-enable supply and wait for target POR */HAL_GPIO_WritePin(cfg->sda_port, cfg->sda_pin, GPIO_PIN_SET);HAL_GPIO_WritePin(cfg->scl_port, cfg->scl_pin, GPIO_PIN_SET);load_switch_enable(slave_index);HAL_Delay(50U);i2c_pins_restore_af(cfg);if (was_initialized) {(void)HAL_I2C_Init(cfg->hi2c);}/* 5. Re-initialize volatile target configuration if needed */if (slave_has_config(slave_index)) {i2c_slave_reinit(slave_index);}return i2c_wait_bus_idle_us(cfg, 20U, 1000U) ? I2C_RECOVER_OK : I2C_RECOVER_ERR_SDA_STUCK_LOW;}
Design rule: For high-availability field systems where whole-board power cycling is unacceptable, place I2C targets behind a TCA9548A switch and/or give each I2C power domain a high-side load switch (with Quick Output Discharge) or dedicated hardware RESET line.
Test both early target release (stopping before extra dummy clocks) and hard-fault detection when SCL or SDA refuses to release:
void test_i2c_recovery_releases_early_on_fifth_clock(void){/* SDA starts low, SCL starts high; mock SDA is indexed by completed SCL pulses (0..9),* so index 5 == 1 simulates the target releasing SDA after the 5th SCL rising edge. */static const uint8_t sda_seq[10] = {0, 0, 0, 0, 0, 1, 1, 1, 1, 1};gpio_mock_set_scl_state(GPIO_PIN_SET);gpio_mock_set_sda_sequence(sda_seq, 10U);i2c_recover_status_t res = i2c_bus_recover(&test_bus_cfg);TEST_ASSERT_EQUAL(I2C_RECOVER_OK, res);TEST_ASSERT_EQUAL(5U, gpio_mock_get_scl_toggle_count());TEST_ASSERT_TRUE(gpio_mock_observed_stop_condition());}void test_i2c_recovery_fails_when_scl_stuck_low(void){gpio_mock_force_scl_low(true);i2c_recover_status_t res = i2c_bus_recover(&test_bus_cfg);TEST_ASSERT_EQUAL(I2C_RECOVER_ERR_SCL_STUCK_LOW, res);TEST_ASSERT_EQUAL(0U, gpio_mock_get_scl_toggle_count());}void test_i2c_recovery_fails_after_9_clocks_if_sda_stuck_low(void){static const uint8_t sda_stuck[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};gpio_mock_set_scl_state(GPIO_PIN_SET);gpio_mock_set_sda_sequence(sda_stuck, 10U);i2c_recover_status_t res = i2c_bus_recover(&test_bus_cfg);TEST_ASSERT_EQUAL(I2C_RECOVER_ERR_SDA_STUCK_LOW, res);TEST_ASSERT_EQUAL(9U, gpio_mock_get_scl_toggle_count());TEST_ASSERT_FALSE(gpio_mock_observed_stop_condition());}
SDA falling while SCL is high (START).NRST pin while the target is shifting out a 0 data bit during a read transfer.NRST and verify SDA remains held low until the controller executes i2c_bus_recover(), stops clocking as soon as SDA releases, issues STOP, and completes the next transfer without HAL_BUSY.RECOVERY_REQ# (or yields while Controller A recovers) rather than pulsing SCL simultaneously.9-clock + STOP + t_BUF quiet window on a logic analyzer and confirm Controller B’s retry succeeds cleanly with zero runt pulses.SDA stuck low after controller reset mid-read or mid-ACKSCL is stuck low and falls back to HW reset or load switch>= t_BUF bus-idle check<= 100 kHz (t_LOW >= 4.7 us, t_HIGH >= 4.0 us)| Scenario | Bus State | Software Recovery | Hardware Provision Needed |
|---|---|---|---|
| Controller reset mid-read / mid-ACK | SDA low, SCL high | 9-clock sequence + STOP | None |
| Target glitch / missed edge | SDA low, SCL high | 9-clock sequence + STOP | None |
| Slow target conversion / write | SCL low (transient) | Wait up to datasheet max stretch | None (or adjust TIMEOUTR) |
SDA latched / shorted to GND | SDA low after 9 clocks | Fails (ERR_SDA_STUCK_LOW) | High-side load switch or RESET# |
SCL frozen / shorted to GND | SCL stays low past timeout | Fails (ERR_SCL_STUCK_LOW) | High-side load switch or RESET# |
| Fault isolated to one branch | Stuck downstream channel | Pulse TCA9548A /RESET | TCA9548A switch + load switch |
Key takeaways:
SCL and SDA first: SCL high with SDA low while idle means a stuck target (run 9-clock recovery), whereas SCL held low indicates clock stretching or a clock-line fault.100 kHz limits: preload GPIO_PIN_SET before switching to GPIO_MODE_OUTPUT_OD, wait for SCL to actually rise before timing t_HIGH, and stop clocking as soon as SDA releases.STOP: confirm SDA released within 9 clocks, issue STOP, and re-initialize the I2C peripheral before starting new transfers.>= t_BUF idle before resuming multi-master traffic.TPS22918 or P-MOSFET) or TCA9548A isolation, and drop SDA/SCL low while VCC discharges so targets actually hit POR.| Symptom | First Check | Likely Cause | Fix |
|---|---|---|---|
HAL_BUSY on first transfer after reset | Read SDA/SCL as GPIO | Target stuck mid-read or mid-ACK | Run i2c_bus_recover() before HAL_I2C_Init |
i2c_bus_recover() passes in debug, fails in release | Check DWT->CTRL / SystemCoreClock | DWT->CYCCNT uninitialized or Cortex-M0 lacks DWT | Enable TRCENA/CYCCNTENA or use TIMx |
I2C_TIMEOUTR_TIMEOUTEN undeclared | Check STM32 CMSIS header | ST spells bit macro I2C_TIMEOUTR_TIMOUTEN | Use I2C_TIMEOUTR_TIMOUTEN (I2C v2 only) |
| Target stays stuck after power-cycle | Measure target VCC during off window | Phantom powering via SDA/SCL pull-ups | Hold SDA/SCL low or isolate via TCA9548A |
TCA9548A channel switch fails | Probe upstream SDA | Stuck downstream channel drags upstream low | Pulse TCA9548A /RESET (>= 6 ns) first |
i2c_generic_scl_recovery() in drivers/i2c/i2c-core-base.cQuick Links
Legal Stuff





