HomeAbout UsContact Us

Fixing I2C Stuck Bus: SDA/SCL Recovery in Multi-Device Sys

By Jithin Tom
Published in Embedded Concepts
November 29, 2026
9 min read
Fixing I2C Stuck Bus: SDA/SCL Recovery in Multi-Device Sys

Table Of Contents

01
Problem Statement: Bus Busy on First Transfer
02
Root Cause Analysis
03
The 9-Clock Recovery Sequence
04
Recovery State Machine
05
Distinguishing Slow Slave from Stuck Slave
06
Multi-Master Arbitration During Recovery
07
Hardware Provisions for Field Recovery
08
Verification and Testing
09
Summary
10
Related Reading
11
References
12
Frequently Asked Questions

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.

Problem Statement: Bus Busy on First Transfer

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 reset
SDA: 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.

Root Cause Analysis

How a Slave Gets Stuck

A target device enters a stuck-bus state through four main mechanisms:

  1. Controller reset mid-transaction: The controller resets (watchdog, brownout, firmware fault, or JTAG halt) while the target is driving 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.
  2. Incomplete power-on reset (POR) or brownout on target: A brief supply dip corrupts internal state-machine flip-flops in a fixed-function sensor or EEPROM without crossing its POR threshold, or partially resets an MCU-based target while leaving an open-drain output latch conducting low.
  3. Spurious clock edges or false address match: Noise glitches or slow rise/fall edges on 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.
  4. Firmware hang in a target ISR: On MCU-based targets with hardware clock stretching enabled (default on STM32 when 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.

Clock Stretching vs. Stuck Bus

ConditionSDA StateSCL StateController Action
Legitimate clock stretchAny (last driven bit or high)Held low by targetWait up to slave max stretch timeout
Stuck bus (SDA low)Held low by targetReleased (high)Run 9-clock recovery + STOP
Stuck bus (SCL low)AnyHeld low beyond max stretchHardware 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.

Why Nine Clock Pulses?

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.

The 9-Clock Recovery Sequence

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.

Timing Constraints

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();
}
}

Handling SMBus Timeout (SMBus vs. I2C)

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);

Recovery State Machine

+-------------------------------------------------------------------------+
| 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 |
| |
+-------------------------------------------------------------------------+

Distinguishing Slow Slave from Stuck Slave

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.

Practical Timeout Strategy

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.

Diagnostic Decision Tree

+-------------------------------------------------------------------------+
| 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) |
| |
+-------------------------------------------------------------------------+

Common False Positives

  1. Undersized or oversized pull-up resistors: Pull-ups that are too weak cause slow RC rise times that read low at the sampling edge; pull-ups that are too strong violate 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_OL
At VDD = 3.3 V: (3.3 - 0.4) / 0.003 A = 967 Ohm
At 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 kOhm
At 400 kHz (t_r <= 300 ns), C_b = 200 pF: 300e-9 / (0.8473 * 200e-12) = 1.77 kOhm
  1. Active host adapters or unpowered probes: A passive high-impedance logic analyzer probe does not pull 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.
  2. Excessive bus capacitance: Long cables or many parallel devices push 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).

Multi-Master Arbitration During Recovery

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.

Master Coordination Protocol

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:

  • Designated Primary Recovery Owner (recommended): Assign recovery and load-switch/reset authority solely to one primary controller (for example, a system supervisor or BMC). Secondary controllers never bit-bang 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.
  • Two-Line Hardware Request/Grant Handshake: Use dedicated 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);
}

Arbitration Loss and Contention During Recovery

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.

Multi-Master Bus Idle Detection

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;
}

Hardware Provisions for Field Recovery

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.

Required Hardware Features

FeaturePurposeCorrect Implementation
High-side load switchPower-cycle an individual target or branchIntegrated 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 lineReset targets without cutting powerActive-low open-drain RESET# pulled up to VDD, driven by controller GPIO
Isolated bus switchIsolate stuck segments from healthy devicesTI TCA9548A 8-channel I2C switch with /RESET pin
Galvanic I2C isolatorBreak ground loops and contain electrical faultsTI ISO1540 (bidirectional SDA + SCL, supports clock stretching and multi-master); use ISO1541 only for single-master, non-stretching buses
Analog bus monitorDiagnose elevated V_OL, weak pull-ups, or contentionHigh-impedance ADC tap on SDA/SCL (keep sampling C_in within C_b budget)

Avoid two common hardware traps:

  1. Low-side N-MOSFET switching: Cutting a target’s ground return with a low-side N-MOSFET (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).
  2. ESD-diode phantom powering: If you turn off a target’s 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.

Bus Segmentation with Multiplexers

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.

Power-Cycle Recovery Sequence

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.

Verification and Testing

Unit Test: 9-Clock Recovery and Early Exit

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());
}

Integration Test: Mid-Transaction Reset

  1. Flash controller and target devices and verify normal repeated reads.
  2. Trigger a logic analyzer capture on SDA falling while SCL is high (START).
  3. Assert the controller NRST pin while the target is shifting out a 0 data bit during a read transfer.
  4. Release 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.

Multi-Master Stress Test

  1. Connect two controllers (one designated primary recovery owner) and at least two targets on a shared bus.
  2. Force a target read hang by resetting Controller A mid-read.
  3. Verify Controller B detects bus busy and requests recovery via RECOVERY_REQ# (or yields while Controller A recovers) rather than pulsing SCL simultaneously.
  4. Capture the 9-clock + STOP + t_BUF quiet window on a logic analyzer and confirm Controller B’s retry succeeds cleanly with zero runt pulses.

Field Test Checklist

  • Pre-init recovery clears SDA stuck low after controller reset mid-read or mid-ACK
  • Recovery aborts cleanly if SCL is stuck low and falls back to HW reset or load switch
  • Legitimate target clock stretches up to worst-case datasheet duration do not trigger false recovery
  • Multi-master systems enforce single recovery owner and continuous >= t_BUF bus-idle check
  • High-side power-cycle path eliminates ESD phantom powering and resets stuck targets cleanly
  • Watchdog fed during long clock-stretch waits or power-cycle discharge windows
  • Recovery timing stays within <= 100 kHz (t_LOW >= 4.7 us, t_HIGH >= 4.0 us)

Summary

ScenarioBus StateSoftware RecoveryHardware Provision Needed
Controller reset mid-read / mid-ACKSDA low, SCL high9-clock sequence + STOPNone
Target glitch / missed edgeSDA low, SCL high9-clock sequence + STOPNone
Slow target conversion / writeSCL low (transient)Wait up to datasheet max stretchNone (or adjust TIMEOUTR)
SDA latched / shorted to GNDSDA low after 9 clocksFails (ERR_SDA_STUCK_LOW)High-side load switch or RESET#
SCL frozen / shorted to GNDSCL stays low past timeoutFails (ERR_SCL_STUCK_LOW)High-side load switch or RESET#
Fault isolated to one branchStuck downstream channelPulse TCA9548A /RESETTCA9548A switch + load switch

Key takeaways:

  1. Check 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.
  2. Preload outputs high and obey 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.
  3. Always finish with a verified STOP: confirm SDA released within 9 clocks, issue STOP, and re-initialize the I2C peripheral before starting new transfers.
  4. Never fake a single-GPIO mutex: assign a single primary recovery owner (or use a two-line request/grant handshake) and require continuous >= t_BUF idle before resuming multi-master traffic.
  5. Prevent phantom powering on power cycles: use high-side load switches (TPS22918 or P-MOSFET) or TCA9548A isolation, and drop SDA/SCL low while VCC discharges so targets actually hit POR.

Debugging Quick Reference

SymptomFirst CheckLikely CauseFix
HAL_BUSY on first transfer after resetRead SDA/SCL as GPIOTarget stuck mid-read or mid-ACKRun i2c_bus_recover() before HAL_I2C_Init
i2c_bus_recover() passes in debug, fails in releaseCheck DWT->CTRL / SystemCoreClockDWT->CYCCNT uninitialized or Cortex-M0 lacks DWTEnable TRCENA/CYCCNTENA or use TIMx
I2C_TIMEOUTR_TIMEOUTEN undeclaredCheck STM32 CMSIS headerST spells bit macro I2C_TIMEOUTR_TIMOUTENUse I2C_TIMEOUTR_TIMOUTEN (I2C v2 only)
Target stays stuck after power-cycleMeasure target VCC during off windowPhantom powering via SDA/SCL pull-upsHold SDA/SCL low or isolate via TCA9548A
TCA9548A channel switch failsProbe upstream SDAStuck downstream channel drags upstream lowPulse TCA9548A /RESET (>= 6 ns) first

References

  1. NXP Semiconductors, UM10204: I2C-bus specification and user manual (Rev. 7.0, October 2021), Sections 3.1.8 “Arbitration”, 3.1.16 “Bus clear”, and 7.1 “Pull-up resistor sizing”
  2. Texas Instruments, SCPA069: I2C Stuck Bus: Prevention and Workarounds (July 2024)
  3. Texas Instruments, SLVA689: I2C Bus Pullup Resistor Calculation (February 2015)
  4. System Management Interface Forum, System Management Bus (SMBus) Specification, Version 3.2 (January 2022)
  5. STMicroelectronics, RM0433: STM32H742, STM32H743/753 and STM32H750 Reference Manual: I2C_TIMEOUTR Register
  6. Texas Instruments, TCA9548A Low-Voltage 8-Channel I2C Switch with Reset Datasheet (SCPS207H, September 2024)
  7. Texas Instruments, ISO1540 and ISO1541 Low-Power Bidirectional I2C Isolators Datasheet (SLLSEB6E, April 2019)
  8. Linux Kernel I2C Subsystem, i2c_generic_scl_recovery() in drivers/i2c/i2c-core-base.c
  9. Total Phase, How to Test and Debug Multi-Master I2C Systems (August 2025)

Frequently Asked Questions

What causes an I2C bus to get stuck with SDA held low?

The most common cause is a controller (master) reset, brownout, or debugger halt mid-transaction while a target (slave) device is driving a 0 bit during a read transfer or holding SDA low on an ACK bit. Less commonly, a target brownout that skips full power-on reset or spurious clock edges from bus noise can desynchronize the target state machine so it holds SDA low indefinitely, preventing any controller from issuing a START condition.

How does the 9-clock recovery sequence work?

The controller places both SCL and SDA in open-drain GPIO mode with SDA released high, verifies SCL is not held low, and clocks SCL up to nine times while polling SDA after each rising edge. Up to nine clocks cover the worst-case remaining 8 data bits plus 1 ACK/NACK bit (leaving SDA high on the 9th clock sends a NACK to a transmitting target). As soon as SDA reads high, the controller stops clocking and generates a STOP condition (SDA low-to-high while SCL is high) to return all targets to idle.

Why must the recovery clock rate stay within the slave's specification?

Target devices rated only for 100 kHz Standard-mode require minimum t_LOW >= 4.7 us and t_HIGH >= 4.0 us, and high pull-up resistance combined with bus capacitance C_b limits how fast SCL rises to V_IH (0.7 * VDD). Clocking SCL faster than the slowest target or bus RC rise time can violate setup/hold margins or fall below input glitch-filter widths, causing the target to miss clock edges and stay stuck.

When is power cycling the only option for bus recovery?

Power cycling or asserting a dedicated hardware RESET line is required when SCL itself is stuck low beyond the maximum legitimate clock-stretch window, or when SDA remains low after nine recovery clock pulses (or up to 16 pulses in non-standard edge cases). This indicates a frozen clock-stretching target, ESD latch-up, transceiver failure, or a physical short to ground. When power-cycling via a high-side load switch, ensure SDA/SCL pull-ups are isolated or pulled low so the target is not phantom-powered through its I/O clamp diodes.

How does multi-master arbitration interact with bus recovery?

Per NXP UM10204 Section 3.1.8, a controller that loses wired-AND arbitration on SDA immediately stops driving data, may continue clocking SCL only until the end of the byte in which arbitration was lost, and then waits for a STOP condition before retrying. During bit-banged bus recovery, hardware arbitration does not protect asynchronous SCL pulses, so systems must designate a single primary recovery owner (or use a two-line request/grant handshake) while other controllers wait for continuous bus idle (>= t_BUF) after recovery.

Tags

i2cdebuggingbus-recoverystuck-busmulti-masterclock-stretching

Share


Previous Article
Fixing Zephyr Mutex PI: Debugging Inheritance Failures
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Fixing UART DMA Idle Line Detection Failures on STM32
Fixing UART DMA Idle Line Detection Failures on STM32
November 25, 2026
8 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media