Skip to content
systemcoding.dev
Embedded

Recover a Stuck I2C Bus by Clocking Out Nine SCL Pulses at Startup

Free an I2C slave holding SDA low after a reset by clocking SCL up to nine times and sending a stop, with a tested C routine and the reason for nine.

8 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Arm, C and STMicroelectronics logos.

A microcontroller resets in the middle of an I2C read. The sensor on the bus does not know: it was halfway through sending a byte, and it keeps SDA pulled low for the bit it was outputting, waiting for a clock pulse that never comes. When the firmware restarts and tries to begin a transaction, SDA is already low, so the START condition (SDA falling while SCL is high) cannot happen, and the I2C peripheral reports the bus as busy forever. Power-cycling the whole board fixes it, which is why the fault looks random in the field. The I2C specification has a recovery for exactly this, called bus clear: toggle SCL up to nine times until the slave releases SDA, then send a STOP. This post explains why nine, implements the routine in portable C, tests it on a host against a model of a stuck slave and shows where to call it. The rule comes from the NXP I2C-bus specification and user manual UM10204, section on bus clear.

Why the bus gets stuck

An I2C slave that is transmitting a byte shifts out one bit per SCL clock pulse, changing SDA while SCL is low. If the master stops clocking in the middle, the slave keeps whatever SDA level corresponds to the current bit. If that bit is a 0, SDA stays low. The slave will not release it until it has been clocked through the rest of its byte and the acknowledge slot.

The usual triggers:

  • The microcontroller resets or crashes during a read (a watchdog reset, a debugger restart, a brown-out).

  • A glitch on SCL corrupts the bit count, so the slave and master disagree on the position within a byte.

  • A hot-plugged device powers up in the middle of a transaction.

  • Noise on a long bus creates a false clock edge.

The master's view is simple: SDA reads low although nobody should be driving it, or the peripheral's BUSY flag stays set and every start request is ignored. On STM32F4, the BUSY bit in I2C_SR2 stays 1 until the bus is released.

Why nine pulses

The slave that is stuck can be at any position within a byte transfer, and it needs enough clock pulses to finish that byte and its acknowledge cycle. A byte occupies nine clocks: eight data bits and the acknowledge. In the worst case the slave has just started a byte (it has just driven bit 7 as 0 and is waiting for the next clock) and needs the remaining seven data bits plus the acknowledge slot: eight more pulses, and one more to move past the point where the master's own ACK or NACK is sampled. UM10204 states the rule directly: if SDA is stuck low, the master should send nine clock pulses, and the device that holds the bus low should release it within those nine clocks.

During the ninth pulse the slave is in the acknowledge position. The master releases SDA and does not pull it low, which presents a NACK, and a slave transmitter that sees a NACK stops sending and releases SDA. After that SDA is high and a STOP condition can be generated cleanly to bring all devices to an idle state.

You can stop earlier: as soon as SDA reads high after a pulse, the slave has released it. The routine checks after each pulse and exits at the first high reading.

The routine

The routine is written against four hooks, so it runs on any microcontroller: set SCL, set SDA, read SDA and read SCL, plus a short delay.

i2c_clear.cc
#include <stdint.h>

typedef struct {
    void (*scl)(int level);       /* 1 = release (let the pull-up raise it), 0 = drive low */
    void (*sda)(int level);
    int  (*read_scl)(void);
    int  (*read_sda)(void);
    void (*delay)(void);          /* about half a period at 100 kHz: 5 microseconds */
} i2c_pins_t;

/* Returns the number of clock pulses used (0 if the bus was already free),
   -1 if SDA never released, -2 if SCL is held low (clock stretching or a fault). */
int i2c_bus_clear(const i2c_pins_t *p)
{
    p->scl(1);
    p->sda(1);
    p->delay();

    if (p->read_scl() == 0) {
        return -2;                            /* SCL held low: cannot clock, see below */
    }
    if (p->read_sda() == 1) {
        return 0;                             /* nothing is stuck */
    }

    int pulses = 0;
    while (pulses < 9 && p->read_sda() == 0) {
        p->scl(0);  p->delay();
        p->scl(1);  p->delay();
        pulses++;
    }
    if (p->read_sda() == 0) {
        return -1;                            /* the slave did not let go */
    }

    /* generate a STOP: SDA low while SCL is low, raise SCL, then raise SDA */
    p->scl(0);  p->delay();
    p->sda(0);  p->delay();
    p->scl(1);  p->delay();
    p->sda(1);  p->delay();
    return pulses;
}

Both lines are treated as open-drain: writing 1 means releasing the pin and letting the pull-up raise it, never driving it high. On a microcontroller that means configuring the pins as open-drain outputs, so the code cannot fight a slave that holds the line low.

The routine returns how many pulses it needed: that information is useful in a log, since a bus that needs a recovery on every boot points at a reset-timing problem.

Testing the routine against a stuck-slave model

The logic is pure C, so test it on a host by modeling a slave that is stuck mid-byte with a given number of bits still to send:

test_clear.cc
#include <stdio.h>
#include <assert.h>
#include "i2c_clear.h"

static int scl_level = 1, sda_master = 1;
static int slave_bits_left;                 /* clock pulses until the slave lets go */
static int prev_scl = 1;

static int slave_pulls_sda(void) { return slave_bits_left > 0; }

static void set_scl(int level)
{
    if (prev_scl == 1 && level == 0 && slave_bits_left > 0) {
        slave_bits_left--;                  /* the slave advances on each falling edge */
    }
    prev_scl = scl_level = level;
}
static void set_sda(int level) { sda_master = level; }
static int  rd_scl(void)       { return scl_level; }
static int  rd_sda(void)       { return sda_master && !slave_pulls_sda(); }
static void dly(void)          { }

int main(void)
{
    i2c_pins_t pins = { set_scl, set_sda, rd_scl, rd_sda, dly };

    slave_bits_left = 0;
    printf("free bus      -> %d\n", i2c_bus_clear(&pins));

    slave_bits_left = 5;
    printf("stuck, 5 bits -> %d\n", i2c_bus_clear(&pins));

    slave_bits_left = 9;
    printf("stuck, 9 bits -> %d\n", i2c_bus_clear(&pins));

    slave_bits_left = 12;
    printf("hung slave    -> %d\n", i2c_bus_clear(&pins));
    return 0;
}
Text
free bus      -> 0
stuck, 5 bits -> 5
stuck, 9 bits -> 9
hung slave    -> -1

The first case needs no pulses. The second releases after 5 pulses, and the routine stops early. The third needs all nine. The last slave needs twelve, more than a legitimate slave ever would, so the routine gives up after nine and reports -1: a device that does not release the bus within nine clocks is broken and needs a hardware reset or a power cycle. In that case the product can pulse a reset line on the sensor, or cut its power with a load switch.

Where to call it on an STM32

The recovery must run before the I2C peripheral takes over the pins. A practical order at start-up:

i2c_startup.cc
#include "stm32f4xx.h"

static void pb6_scl(int l) { GPIOB->BSRR = l ? (1u << 6) : (1u << (6 + 16)); }
static void pb7_sda(int l) { GPIOB->BSRR = l ? (1u << 7) : (1u << (7 + 16)); }
static int  pb6_read(void) { return (GPIOB->IDR >> 6) & 1u; }
static int  pb7_read(void) { return (GPIOB->IDR >> 7) & 1u; }
static void us5(void)      { for (volatile int i = 0; i < 100; i++) { __NOP(); } }

int i2c1_startup_recover(void)
{
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN;
    (void)RCC->AHB1ENR;

    GPIOB->OTYPER |= (1u << 6) | (1u << 7);                              /* open-drain */
    GPIOB->BSRR = (1u << 6) | (1u << 7);                                 /* released */
    GPIOB->MODER = (GPIOB->MODER & ~((3u << 12) | (3u << 14)))
                 | (1u << 12) | (1u << 14);                              /* general-purpose outputs */

    i2c_pins_t pins = { pb6_scl, pb7_sda, pb6_read, pb7_read, us5 };
    int rc = i2c_bus_clear(&pins);

    /* hand the pins to the I2C peripheral (alternate function 4) */
    GPIOB->MODER = (GPIOB->MODER & ~((3u << 12) | (3u << 14)))
                 | (2u << 12) | (2u << 14);
    return rc;
}

int main(void)
{
    int rc = i2c1_startup_recover();
    printf("bus clear: %d\n", rc);
    i2c1_init_400k();
    /* ... normal operation ... */
}

With open-drain outputs the code can read the real pin level through IDR even while the pin is configured as an output, since the input buffer stays connected on STM32 GPIO. The delay of about 5 microseconds per half period gives roughly 100 kHz, comfortably slower than any device's minimum; calibrate it on your clock or use a timer.

A cold boot with a healthy bus prints:

Text
bus clear: 0

and after a reset in mid-read, with a sensor that needed 5 pulses to finish its byte:

Text
bus clear: 5

Recovery at run time

The same routine belongs in the error path of the driver: when a transaction times out or the peripheral reports a bus error, disable the peripheral, run the bus clear on the pins, reset the peripheral (on the F4, set and clear SWRST in I2C_CR1) and retry. The guide to I2C in this cluster shows the integration with retry counters. Count each recovery; if recoveries keep recurring in the field, the cause is upstream: a weak pull-up, noise or a slave with a firmware bug.

When SCL is the stuck line

The routine can only fix a stuck SDA. If SCL itself is held low, the master cannot generate clock pulses, because it cannot make SCL go high. Causes: a slave stretching the clock indefinitely (a crashed slave microcontroller), a short, a damaged device or a missing pull-up. The routine detects it by reading SCL after releasing and returns -2. Nothing in software helps here: reset or power-cycle the offending device, which means designing the board so it can be done, with a reset line or a switchable supply on each device that might hang the bus. Some designs add an I2C bus buffer or multiplexer with a reset input that isolates a misbehaving branch.

Other limits worth knowing:

  • Two stuck conditions at once. A slave holding SDA low and another holding SCL low need separate treatment.

  • Multi-master buses. Do not clock a bus that another master may be using; coordinate or wait for a timeout.

  • A slave that needs a STOP to leave its state. The final STOP in the routine takes care of this.

  • The peripheral's own lock-up. On the STM32F4 I2C block, the peripheral can stay busy even after the lines are free; the software reset bit is the cure.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.