The Complete Guide to I2C on Microcontrollers
Learn I2C from the open-drain wires up: addresses, ACK, repeated start, pull-up sizing, STM32 register code, bus scans, clock stretching and recovery.

I2C is the bus that puts a dozen sensors, a clock chip, an EEPROM and a display on two wires. That economy is why it is everywhere, and also why it fails in ways that SPI and UART do not: a device that holds the data line low and freezes the whole bus, a pull-up resistor that is too weak for the cable, an address that two chips share, a read that returns the wrong register because the protocol needs a repeated start and the code sent a stop. Almost every I2C problem comes from one of five places: the pull-up resistors, the address, the start and stop sequence, the clock stretching a device performs, or a bus that locked up and was never recovered. This guide builds the subject in that order. It covers the open-drain electrical model and how to size the pull-ups, the byte-level protocol with start, stop, address, acknowledge and repeated start, a register-level master driver for an STM32F407 (reference manual RM0090), the standard register-read pattern, a bus scanner, clock stretching, error handling and recovery, multi-master arbitration in brief, and a method for debugging with a logic analyzer. The rules come from the NXP I2C-bus specification and user manual UM10204. The central fact to carry through: an I2C wire can only be pulled low by a device and is pulled high by a resistor, so the speed of every rising edge is set by a resistor and the capacitance of the bus.
The two wires and why they are open-drain
I2C uses two signals, shared by every device on the bus:
| Signal | Name | Purpose |
|---|---|---|
| SDA | Serial data | Carries addresses and data, in both directions |
| SCL | Serial clock | Driven by the controller (the master); the clock for every bit |
Both lines are open-drain (open-collector): a device can pull a line to ground or release it, but never drives it high. A pull-up resistor from each line to the supply provides the high level. A line is high only if every device is releasing it, and low if any device pulls it down. That is a wired-AND, and it is the feature that makes two things possible: several devices can share a line without damaging each other if two transmit at once, and a slow device can hold SCL low to make the master wait, called clock stretching.
The cost of the open-drain design is the rising edge. A falling edge is fast because a transistor pulls the line down hard. A rising edge is an RC charge through the pull-up resistor into the capacitance of the wires and the device pins, so it rises exponentially. The speed of the bus is limited by the rise time, which is set by the resistor and the capacitance.
Sizing the pull-up resistors
The specification limits both rise time and the current a device must sink. For a pull-up resistor Rp to a supply Vdd:
The maximum value comes from the rise time. The signal must rise from 30 percent to 70 percent of
Vddwithin the allowed timetr: 1000 ns in standard mode (100 kHz), 300 ns in fast mode (400 kHz) and 120 ns in fast mode plus (1 MHz). The 30 to 70 percent rise of an RC circuit takes about0.8473 * Rp * Cb, whereCbis the total bus capacitance, so:
Rp(max) = tr / (0.8473 * Cb)The minimum value comes from the sink current. When a device pulls the line low it must hold it below
VOL(max), 0.4 V, while sinking at most 3 mA in standard and fast mode:
Rp(min) = (Vdd - 0.4 V) / 3 mAWork an example for a 3.3 V bus with 100 pF of capacitance (about four devices and a few centimeters of trace) at 400 kHz:
Rp(min) = (3.3 - 0.4) / 0.003 = 967 ohm
Rp(max) = 300e-9 / (0.8473 * 100e-12) = 3,541 ohmAny standard value between about 1 k and 3.5 k works, and 2.2 k or 3.3 k are typical. At 100 kHz with the same capacitance the maximum rises to 11.8 k, so 4.7 k is common for standard mode. The specification allows a total bus capacitance of up to 400 pF. A long cable or many devices raise Cb, and the usable resistor range narrows: at 400 pF and 400 kHz, Rp(max) = 300e-9 / (0.8473 * 400e-12) = 885 ohm, which is already below Rp(min), so such a bus cannot run at 400 kHz and must drop to 100 kHz or use an active bus buffer.
A short program turns these formulas into a calculator for any case:
#include <stdio.h>
static void pullup(double vdd, double cb_pf, double tr_ns)
{
double rmin = (vdd - 0.4) / 0.003;
double rmax = (tr_ns * 1e-9) / (0.8473 * cb_pf * 1e-12);
printf("Vdd=%.1f Cb=%3.0f pF tr=%4.0f ns -> Rp %.0f .. %.0f ohm%s\n",
vdd, cb_pf, tr_ns, rmin, rmax, rmax < rmin ? " (no valid value)" : "");
}
int main(void)
{
pullup(3.3, 100.0, 1000.0); /* standard mode */
pullup(3.3, 100.0, 300.0); /* fast mode */
pullup(3.3, 400.0, 300.0); /* fast mode, heavy bus */
return 0;
}Vdd=3.3 Cb=100 pF tr=1000 ns -> Rp 967 .. 11803 ohm
Vdd=3.3 Cb=100 pF tr= 300 ns -> Rp 967 .. 3541 ohm
Vdd=3.3 Cb=400 pF tr= 300 ns -> Rp 967 .. 885 ohm (no valid value)Two practical notes. Many sensor breakout boards already carry pull-ups of 4.7 k or 10 k; several boards on one bus put them in parallel, so three boards with 4.7 k pull-ups give 1.57 k, which may be too low for a 5 V bus but is fine at 3.3 V. And the microcontroller's internal pull-ups (typically 30 to 50 k) are far too weak for I2C above a few kilohertz on all but the shortest wires; use external resistors.
The protocol, bit by bit
All of I2C is a handful of bus conditions and one byte format.
Data validity. SDA may change only while SCL is low. While SCL is high, SDA must be stable. That is how a bit is sent: set SDA while SCL is low, raise SCL, the receiver samples SDA, lower SCL.
START condition. SDA falls while SCL is high. It marks the beginning of a transaction and, because it breaks the data-validity rule on purpose, every device recognizes it.
STOP condition. SDA rises while SCL is high. It ends the transaction and frees the bus.
Repeated start. A START sent without a preceding STOP. It keeps the bus owned by the master while changing direction, which is how you write a register address and then read its contents without letting another master in.
Byte format. Eight data bits, most significant bit first, then a ninth clock for the acknowledge. The receiver pulls SDA low during the ninth clock to acknowledge (ACK) and leaves it high for no acknowledge (NACK). So each byte takes nine clocks.
Address. The first byte after a START is the address byte: seven address bits and one read/write bit.
| Bit 7 to 1 | Bit 0 |
|---|---|
| 7-bit device address | 0 = master writes, 1 = master reads |
A device with address 0x68 is addressed with byte 0xD0 for a write (0x68 << 1) and 0xD1 for a read. Documentation is inconsistent about whether an address is quoted as 7 bits (0x68) or as the 8-bit write byte (0xD0). Check which one a datasheet and a library use; mixing them up is the classic reason a scan finds nothing at the expected address.
A write transaction, sending two bytes to register 0x6B of a device at 0x68:
S | 0x68<<1|W | A | 0x6B | A | 0x00 | A | PS is the start, W the write bit (0), A the ACK from the device after each byte and P the stop. Three bytes go out, each followed by an ACK: the address byte, the register number and the data.
A register read uses a repeated start to change direction:
S | 0x68<<1|W | A | 0x75 | A | Sr | 0x68<<1|R | A | data | N | PThe master writes the register address 0x75, issues a repeated start Sr, addresses the device again for reading, receives the data byte and then sends a NACK (N) on that last byte to tell the device to stop sending, followed by a stop. The NACK on the final byte of a read is the master's way to say "that is enough". Forgetting it, so that the master ACKs the last byte, leaves the device holding SDA for the next byte and often locks the bus.
Addresses to avoid
Seven bits give 128 addresses, but 16 are reserved by the specification: 0x00 to 0x07 (general call, start byte, CBUS, high-speed mode and others) and 0x78 to 0x7F (10-bit addressing and reserved). Usable addresses are 0x08 to 0x77. A scanner should skip the reserved ranges.
A register-level master on the STM32F407
The STM32F4 I2C peripheral is a master or slave that handles the bus timing and the bit-level protocol, leaving byte-level sequencing to software. The key registers:
| Register | Purpose |
|---|---|
I2C_CR1 | PE enable, START, STOP, ACK, SWRST |
I2C_CR2 | FREQ field: the APB1 clock in MHz |
I2C_CCR | Clock control: sets SCL period, F/S fast mode, DUTY |
I2C_TRISE | Maximum rise time, in peripheral clock cycles plus one |
I2C_DR | Data register |
I2C_SR1 | Flags: SB start sent, ADDR address sent, BTF byte transfer finished, TXE, RXNE, AF ack failure, BERR, ARLO |
I2C_SR2 | BUSY, MSL master, TRA transmitter |
Two notes about this peripheral. It is the older I2C design used on the STM32F1, F2 and F4 families, with documented quirks and a strict event sequence; the I2C of the STM32 families from L4, G0 and G4 onward uses a different register layout (TIMINGR, ISR, TXDR, RXDR) that does much of the sequencing in hardware. And on the F4 the I2C block can lock up if the sequence is disturbed, which is why the recovery section matters.
Pins and clocks
I2C1 uses PB6 for SCL and PB7 for SDA as alternate function 4, with both pins configured as open-drain. Internal pull-ups are off; external resistors are on the board.
#include "stm32f4xx.h"
#include <stdint.h>
#define PCLK1_MHZ 42u
void i2c1_init_400k(void)
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN;
RCC->APB1ENR |= RCC_APB1ENR_I2C1EN;
(void)RCC->APB1ENR;
/* PB6 = SCL, PB7 = SDA: alternate function 4, open-drain, no internal pull */
GPIOB->MODER = (GPIOB->MODER & ~((3u << 12) | (3u << 14))) | (2u << 12) | (2u << 14);
GPIOB->OTYPER |= (1u << 6) | (1u << 7);
GPIOB->OSPEEDR |= (2u << 12) | (2u << 14);
GPIOB->PUPDR &= ~((3u << 12) | (3u << 14));
GPIOB->AFR[0] = (GPIOB->AFR[0] & ~((0xFu << 24) | (0xFu << 28))) | (4u << 24) | (4u << 28);
I2C1->CR1 = I2C_CR1_SWRST; /* reset the peripheral */
I2C1->CR1 = 0;
I2C1->CR2 = PCLK1_MHZ; /* tell the peripheral the APB1 frequency */
I2C1->CCR = I2C_CCR_FS | 35u; /* fast mode, duty 2:1: 42e6 / (3 * 400e3) = 35 */
I2C1->TRISE = 13u; /* 300 ns / 23.8 ns = 12.6, plus 1 */
I2C1->CR1 |= I2C_CR1_PE;
}The numbers come from the reference manual's formulas. In fast mode with DUTY = 0 the clock is low for twice as long as it is high, so the period is three CCR units and CCR = PCLK1 / (3 * f_SCL) = 42,000,000 / 1,200,000 = 35. The TRISE register holds the maximum allowed rise time in peripheral-clock units plus one: with a 42 MHz clock one cycle is 23.8 ns, the 300 ns limit is 12.6 cycles, truncated to 12, plus one gives 13. For standard mode at 100 kHz, CCR = 42,000,000 / (2 * 100,000) = 210 and TRISE = 1000 / 23.8 + 1 = 43.
Writing bytes
The master write follows the event sequence of the reference manual:
static int i2c_wait(volatile uint32_t *reg, uint32_t mask, uint32_t timeout)
{
while (((*reg) & mask) == 0u) {
if (timeout-- == 0u) return -1;
}
return 0;
}
int i2c1_write(uint8_t addr7, const uint8_t *data, uint32_t len)
{
if (i2c_wait(&I2C1->SR2, 0, 1) < 0) return -1;
while (I2C1->SR2 & I2C_SR2_BUSY) { } /* bus must be idle */
I2C1->CR1 |= I2C_CR1_START;
if (i2c_wait(&I2C1->SR1, I2C_SR1_SB, 100000) < 0) return -1;
I2C1->DR = (uint8_t)(addr7 << 1); /* address + write */
if (i2c_wait(&I2C1->SR1, I2C_SR1_ADDR | I2C_SR1_AF, 100000) < 0) return -1;
if (I2C1->SR1 & I2C_SR1_AF) { /* no device acknowledged */
I2C1->SR1 &= ~I2C_SR1_AF;
I2C1->CR1 |= I2C_CR1_STOP;
return -2;
}
(void)I2C1->SR1; (void)I2C1->SR2; /* clear ADDR: read SR1 then SR2 */
for (uint32_t i = 0; i < len; i++) {
if (i2c_wait(&I2C1->SR1, I2C_SR1_TXE, 100000) < 0) return -1;
I2C1->DR = data[i];
}
if (i2c_wait(&I2C1->SR1, I2C_SR1_BTF, 100000) < 0) return -1; /* last byte fully sent */
I2C1->CR1 |= I2C_CR1_STOP;
return 0;
}Walking through it: START sets the SB flag when the condition is on the wire; writing the address to DR clears it and starts the address phase. The ADDR flag means an address byte was acknowledged; the flag AF means no one acknowledged. ADDR clears only by reading SR1 and then SR2, a quirk of this peripheral. Each data byte waits for TXE. The final wait is on BTF, byte transfer finished, which means the last byte has fully left the shift register, and only then is STOP safe. Setting STOP right after the last TXE truncates the final byte.
Every wait carries a timeout, because an absent device or a stuck bus would otherwise hang the program.
Reading a register
The standard pattern is write the register address, repeated start, read. Reading a single byte on this peripheral needs a particular order, because the peripheral must be told to NACK the last byte before it arrives:
int i2c1_read_reg(uint8_t addr7, uint8_t reg, uint8_t *out)
{
while (I2C1->SR2 & I2C_SR2_BUSY) { }
I2C1->CR1 |= I2C_CR1_START;
if (i2c_wait(&I2C1->SR1, I2C_SR1_SB, 100000) < 0) return -1;
I2C1->DR = (uint8_t)(addr7 << 1); /* write phase */
if (i2c_wait(&I2C1->SR1, I2C_SR1_ADDR | I2C_SR1_AF, 100000) < 0) return -1;
if (I2C1->SR1 & I2C_SR1_AF) { I2C1->SR1 &= ~I2C_SR1_AF; I2C1->CR1 |= I2C_CR1_STOP; return -2; }
(void)I2C1->SR1; (void)I2C1->SR2;
if (i2c_wait(&I2C1->SR1, I2C_SR1_TXE, 100000) < 0) return -1;
I2C1->DR = reg; /* register address */
if (i2c_wait(&I2C1->SR1, I2C_SR1_BTF, 100000) < 0) return -1;
I2C1->CR1 |= I2C_CR1_START; /* repeated start */
if (i2c_wait(&I2C1->SR1, I2C_SR1_SB, 100000) < 0) return -1;
I2C1->DR = (uint8_t)((addr7 << 1) | 1u); /* read phase */
if (i2c_wait(&I2C1->SR1, I2C_SR1_ADDR, 100000) < 0) return -1;
I2C1->CR1 &= ~I2C_CR1_ACK; /* NACK the only byte */
(void)I2C1->SR1; (void)I2C1->SR2; /* clear ADDR */
I2C1->CR1 |= I2C_CR1_STOP; /* stop after this byte */
if (i2c_wait(&I2C1->SR1, I2C_SR1_RXNE, 100000) < 0) return -1;
*out = (uint8_t)I2C1->DR;
I2C1->CR1 |= I2C_CR1_ACK; /* restore for later transfers */
return 0;
}For a single-byte read the reference manual says to clear ACK and program STOP after clearing ADDR, which is why those lines come in that order. With an InvenSense MPU-6050 at address 0x68, the register WHO_AM_I at 0x75 returns 0x68:
int main(void)
{
i2c1_init_400k();
uint8_t id = 0;
int rc = i2c1_read_reg(0x68, 0x75, &id);
printf("rc=%d WHO_AM_I=0x%02X\n", rc, id);
for (;;) { }
}rc=0 WHO_AM_I=0x68The return code is 0, and the sensor reports its identity. A return of -2 means no device acknowledged the address; -1 means a timeout and usually a bus problem.
The read of several bytes follows the same shape with ACK set for all but the last byte, with a special case for the last two bytes that the reference manual documents. This is why most projects use the HAL's HAL_I2C_Mem_Read, covered in its own post, instead of writing the sequence by hand.
Scanning the bus
A scan sends an address with a write bit and watches for the ACK. A device that exists acknowledges, and the master sees ADDR set; an absent one produces AF:
int i2c1_probe(uint8_t addr7)
{
while (I2C1->SR2 & I2C_SR2_BUSY) { }
I2C1->CR1 |= I2C_CR1_START;
if (i2c_wait(&I2C1->SR1, I2C_SR1_SB, 100000) < 0) return -1;
I2C1->DR = (uint8_t)(addr7 << 1);
while ((I2C1->SR1 & (I2C_SR1_ADDR | I2C_SR1_AF)) == 0u) { }
int present = (I2C1->SR1 & I2C_SR1_ADDR) != 0u;
if (present) { (void)I2C1->SR1; (void)I2C1->SR2; }
I2C1->SR1 &= ~I2C_SR1_AF;
I2C1->CR1 |= I2C_CR1_STOP;
while (I2C1->CR1 & I2C_CR1_STOP) { }
return present;
}
void i2c1_scan(void)
{
for (uint8_t a = 0x08; a <= 0x77; a++) {
if (i2c1_probe(a) == 1) {
printf("device at 0x%02X\n", a);
}
}
}With an MPU-6050 and a BMP280 on the bus:
device at 0x68
device at 0x76A scan is the best first test of a new I2C board. If nothing appears, check power, pull-ups, the address range and the wiring before suspecting code. If a device appears at an unexpected address, the address-select pin is wired differently from what you assumed. A scan also has side effects on some devices (a write-address probe can be interpreted by an EEPROM as the start of a write), so avoid scanning a bus with devices that misbehave on it.
Clock stretching
A device that needs more time can hold SCL low after the master has released it. The master must notice, because it must not raise its next clock edge until SCL actually goes high. The I2C peripheral does this automatically in hardware. A bit-banged master must read SCL back after releasing it and wait.
Typical cases where stretching occurs: a sensor completing a measurement before returning data (the Bosch BMP280 does not stretch, but several humidity and temperature sensors do), and slave microcontrollers that need time to process a byte in an interrupt. A master that ignores stretching reads garbage because it samples before the data is ready. A master peripheral with a timeout bit (SMBTIMEOUT and the timeout register on the newer STM32 I2C) can abort if a slave holds SCL low longer than the SMBus limit of 35 milliseconds, which protects against a hung slave.
The reverse also matters: a slave microcontroller that stretches too long slows the whole bus for every other device. Keep slave handlers short.
Bus errors and recovery
The status flags tell you what went wrong:
| Flag | Meaning | Usual cause |
|---|---|---|
AF | Acknowledge failure | No device at that address, device busy, wrong address |
BERR | Bus error | A start or stop appeared at an illegal moment, noise or a glitch |
ARLO | Arbitration lost | Another master is on the bus |
OVR | Overrun or underrun | Software too slow in slave mode |
TIMEOUT | SCL held low too long | A hung device |
The worst failure is a stuck bus: a device holds SDA low because it was interrupted in the middle of sending a byte (for example, when the master was reset during a read) and is waiting for clock pulses to finish. The master's start condition cannot happen because SDA is not high. On the F4 the BUSY flag then stays set permanently, and the peripheral cannot be used until the bus is freed.
The recovery from the specification: temporarily take control of the pins as general-purpose outputs, toggle SCL up to nine times until the device releases SDA, then generate a stop condition, then hand the pins back to the peripheral:
static void delay_us(uint32_t us) { for (volatile uint32_t i = 0; i < us * 20u; i++) { } }
void i2c1_bus_recover(void)
{
I2C1->CR1 &= ~I2C_CR1_PE;
/* SCL (PB6) as open-drain output, SDA (PB7) as open-drain output, both released high */
GPIOB->MODER = (GPIOB->MODER & ~((3u << 12) | (3u << 14))) | (1u << 12) | (1u << 14);
GPIOB->BSRR = (1u << 6) | (1u << 7);
for (int i = 0; i < 9 && !(GPIOB->IDR & (1u << 7)); i++) {
GPIOB->BSRR = (1u << (6 + 16)); delay_us(5); /* SCL low */
GPIOB->BSRR = (1u << 6); delay_us(5); /* SCL high */
}
/* generate a STOP: SDA low, SCL high, SDA high */
GPIOB->BSRR = (1u << (7 + 16)); delay_us(5);
GPIOB->BSRR = (1u << 6); delay_us(5);
GPIOB->BSRR = (1u << 7); delay_us(5);
/* give the pins back to I2C and reset the peripheral */
GPIOB->MODER = (GPIOB->MODER & ~((3u << 12) | (3u << 14))) | (2u << 12) | (2u << 14);
I2C1->CR1 |= I2C_CR1_SWRST;
I2C1->CR1 &= ~I2C_CR1_SWRST;
i2c1_init_400k();
}Call it at start-up if the bus is busy, and whenever a transfer times out. The dedicated post on clocking out nine SCL pulses explains why nine is the number.
Arbitration and multi-master
I2C allows several masters on one bus. When two start at the same time, both drive and monitor SDA. The first to send a 1 while the line reads 0 (because the other pulled it low) has lost arbitration and stops sending, without any data corruption: the winner continues unaware. The loser sees ARLO and must retry later. Because the wired-AND resolves the clash, no extra hardware is needed. Most designs have one master, but the feature matters when two processors share a sensor bus, and some firmware must handle ARLO correctly even when it believes it is the only master, since noise can look like another master.
10-bit addressing, SMBus and speeds
The specification defines a 10-bit address mode, signaled by a reserved first byte 11110xx, for buses with more than 112 usable addresses. Few devices use it. SMBus, defined by Intel and used in power management and laptop batteries, is a stricter relative of I2C: it limits the clock to 10 to 100 kHz, requires a timeout on a stuck clock and defines packet error checking. Many I2C devices work on an SMBus and the reverse is also usually true.
Speed modes:
| Mode | Maximum SCL | Max rise time |
|---|---|---|
| Standard | 100 kHz | 1000 ns |
| Fast | 400 kHz | 300 ns |
| Fast-mode Plus | 1 MHz | 120 ns |
| High-speed | 3.4 MHz | needs special drive |
| Ultra-fast | 5 MHz, write-only | push-pull |
A bus runs at the speed of its slowest device. Mixing a 100 kHz-only part with 400 kHz parts forces the whole bus down unless a bus switch isolates the slow segment.
I2C on other platforms
The wire protocol is the same everywhere; the APIs differ and, in all of them, a register read is a write of the register address followed by a read.
| Platform | Initialize | Register read |
|---|---|---|
Arduino Wire | Wire.begin() | Wire.beginTransmission, Wire.write(reg), Wire.endTransmission(false), Wire.requestFrom |
| Pico SDK | i2c_init(i2c0, 400000) and gpio_set_function | i2c_write_blocking(..., nostop = true) then i2c_read_blocking |
| ESP-IDF | i2c_new_master_bus, i2c_master_bus_add_device | i2c_master_transmit_receive |
| STM32 HAL | HAL_I2C_Init | HAL_I2C_Mem_Read |
The "no stop" flag in the Arduino and Pico calls is the repeated start. Wire.endTransmission(false) keeps the bus, and the default true sends a stop and breaks register reads on devices that need the repeated start. Each of these platforms has its own post in this cluster.
Debugging with a logic analyzer
The most reliable approach is to look at the wire. Connect two analyzer channels to SCL and SDA with ground, sample at 10 times the bus clock or more (4 MHz for a 400 kHz bus), and use the I2C protocol decoder in PulseView, which shows start, address, read or write, ACK or NACK and each data byte. Work through these checks:
Idle levels. Both lines must sit high between transactions. A line stuck low means a hung device or a missing pull-up.
Rise time. Zoom into a rising edge. A slow, rounded edge that does not reach the supply within the allowed time means the pull-up is too weak or the capacitance too high.
Address ACK. After the address byte the ninth bit should be low. A NACK means wrong address, an unpowered device or a bad connection.
The sequence. For a register read, confirm there is a repeated start between the register write and the read, and a NACK on the last byte.
Stretching. SCL held low by a device after the master released it shows as a long low pulse; compare with the datasheet.
Noise. Runt pulses or glitches on SDA while SCL is high create false start and stop conditions.
| Symptom | Likely cause |
|---|---|
| Scan finds nothing | No power, no pull-ups, SDA and SCL swapped, wrong pins |
| Scan finds a device at the wrong address | Address pin wired differently, 7-bit versus 8-bit confusion |
| Works at 100 kHz, fails at 400 kHz | Pull-ups too weak, bus capacitance too high |
| Reads return the previous register | Missing repeated start, stop sent between write and read |
| Bus hangs after a reset | Device stuck holding SDA low; run the recovery sequence |
| Intermittent errors with long wires | Capacitance and noise; lower the speed, strengthen pull-ups, shield |
| Two devices both answer | Address clash; change address pins or use a multiplexer |
Several identical devices
Two chips with the same fixed address cannot share a bus. Three remedies: use address-select pins if the part has them (an EEPROM like the 24C32 offers three), use an I2C multiplexer such as the TCA9548A, which switches one of eight downstream buses onto the upstream bus under software control, or put the chips on separate buses. A multiplexer adds a layer of software: select the channel, talk to the device, optionally deselect.
Reading a decoded capture
A logic analyzer's I2C decoder prints the transaction as text. Learning to read that text quickly is the most useful debugging skill on this bus. Here is the register read from the earlier example as the decoder shows it:
Start
Address write: 0x68 ACK
Data write: 0x75 ACK
Start repeat
Address read: 0x68 ACK
Data read: 0x68 NACK
StopEvery line maps to something in the protocol: the first address byte carries the write bit and the device acknowledged, the register number 0x75 was acknowledged, the repeated start switched direction, the read address was acknowledged, the device sent 0x68, and the master ended the transfer with a NACK and a stop. A healthy transaction has an ACK after every byte except the last one the master reads. When something is wrong the text points straight at it: a NACK after the first address means nobody answered, a NACK after the register number means the device rejected the register (some chips NACK writes to read-only or reserved registers), and a stop where a repeated start should be explains why a read returns stale data.
The timing of that transaction at 400 kHz follows from counting clocks. There are 3 address and register bytes of 9 clocks each, one repeated start, one data byte of 9 clocks and the framing conditions: roughly 27 + 9 + 2 = 38 clock periods of 2.5 microseconds, about 95 microseconds in total. A programmer who expects a 1 kHz sample loop to read ten registers in each pass should do this arithmetic first: ten such reads take about a millisecond, which is the whole period. Reading a block of consecutive registers in one transaction, using the device's auto-increment, saves the repeated address phases and cuts that time by a factor of several.
Registers wider than one byte
Many devices use more than one byte for the register address, and many registers hold more than one byte of data. Serial EEPROMs of 4 KB and larger, such as the 24C32 and 24C64, take a 16-bit memory address, sent high byte first. A byte write looks like this:
S | 0x50<<1|W | A | addr_hi | A | addr_lo | A | data | A | Pand a read of one byte at a random address sends the two address bytes, then a repeated start and the read address:
int eeprom_read(uint16_t mem_addr, uint8_t *dst, uint32_t len)
{
uint8_t addr_bytes[2] = { (uint8_t)(mem_addr >> 8), (uint8_t)mem_addr };
if (i2c1_write_no_stop(0x50, addr_bytes, 2) != 0) return -1;
return i2c1_read_after_restart(0x50, dst, len);
}A 24C32 write needs one more rule that surprises many people: after the stop that ends a write, the chip performs an internal write cycle of up to 5 milliseconds (the datasheet's tWR), during which it does not acknowledge its address. The standard way to wait is acknowledge polling: repeat START plus the device address until the device ACKs, rather than sleeping a fixed time:
int eeprom_wait_ready(uint32_t timeout_ms)
{
uint32_t start = HAL_GetTick();
while (i2c1_probe(0x50) != 1) {
if (HAL_GetTick() - start > timeout_ms) return -1;
}
return 0;
}Also respect the page size: a write that crosses the page boundary (32 bytes on a 24C32) wraps within the page and overwrites its start. Multi-byte data in the sensor registers raises a different question: byte order. Many sensors, such as the MPU-6050, send the high byte of a 16-bit value first, while others, such as many ST parts, send the low byte first. Check the datasheet, and if you read the two bytes in separate transactions, a value that changes between the reads gives a corrupt result, which is why block reads are safer.
A small driver structure that survives real hardware
Production I2C code needs the same four ingredients every time: a timeout on every wait, a retry for transient errors, a recovery path for a stuck bus and a place to count what happened. Wrapping the low-level calls in one function that implements all four keeps device drivers short:
typedef enum { I2C_OK = 0, I2C_NACK = -2, I2C_TIMEOUT = -1, I2C_BUS = -3 } i2c_status_t;
typedef struct {
uint32_t transfers, nacks, timeouts, recoveries;
} i2c_stats_t;
static i2c_stats_t stats;
i2c_status_t i2c_read_reg_retry(uint8_t addr7, uint8_t reg, uint8_t *out)
{
for (int attempt = 0; attempt < 3; attempt++) {
stats.transfers++;
int rc = i2c1_read_reg(addr7, reg, out);
if (rc == 0) return I2C_OK;
if (rc == -2) { stats.nacks++; return I2C_NACK; } /* no point retrying */
stats.timeouts++;
i2c1_bus_recover(); /* timeout: free the bus */
stats.recoveries++;
}
return I2C_TIMEOUT;
}A NACK is returned immediately because a missing device will not appear on a retry, while a timeout triggers recovery and another attempt. The counters tell you in the field whether errors are frequent: a handful of recoveries over days is normal on a noisy product; hundreds per hour means a hardware problem such as a weak pull-up or a marginal connector.
Level shifting and mixed voltages
Open-drain buses can be level shifted cheaply because the lines are bidirectional by nature. The classic circuit uses one N-channel MOSFET per line, with the gate tied to the low-voltage supply, the source to the low-voltage side and the drain to the high-voltage side, and a pull-up on each side. When the low side pulls a line low, the MOSFET conducts and pulls the high side low as well. When the high side pulls low, the body diode and then the channel pull the low side low. Both ends see a valid high through their own pull-up. Dedicated I2C level translators such as the PCA9306 do the same in one package. A direction-controlled buffer for push-pull signals, which works for SPI, will not work for I2C, because the same pin is an input and an output at different moments.
If the microcontroller's pins are not 5 V tolerant, never connect a 5 V pull-up to them. Check the datasheet for "FT" or "5 V tolerant" markings and, for STM32 parts, remember that tolerance is lost when the pin is in analog mode and when the part's supply is off.
Hot-plugging and power sequencing
When one device on the bus is powered off, its pins must not pull the shared lines low through clamp diodes to its supply rail. Most modern I2C parts are specified to leave the lines high-impedance with the supply off, but older or cheaper parts are not, and a powered-down sensor board can hold a bus at 0.7 V and make every other device unreachable. Test this by powering the bus with one device removed from supply, and look at SDA and SCL with a multimeter: they should sit at the pull-up voltage. For connectors that are plugged live, add a bus buffer with hot-swap support, and plan for the bus-recovery routine to run after insertion.
A worked bus budget
Putting the pieces together for a design: five sensors, a real-time clock and an EEPROM on one 3.3 V bus at 400 kHz, each sensor read once per 10 ms as a 6-byte block, the clock once per second and the EEPROM occasionally. Each sensor read is a 3-byte address phase plus six data bytes plus the framing:
clocks per read = 3 * 9 + 6 * 9 + 2 = 83 time = 83 / 400,000 = 207.5 microseconds
five sensors every 10 ms: 5 * 207.5 = 1.04 ms of every 10 ms -> 10.4 percent bus utilizationThat leaves nearly 90 percent of the bus free, so the design has room. If the same five sensors were read every millisecond, utilization would be 104 percent, which is impossible: the bus cannot keep up, and the design must either lower the rate, read fewer bytes, move the fast sensors to SPI or split the sensors across two buses. Doing the clock count first prevents building a driver around a bus that cannot carry the load. Capacitance is the second budget: six devices at roughly 10 pF each plus 10 cm of trace at about 1 pF per centimeter is 70 pF, below the 400 pF limit and consistent with the 1 k to 3.5 k pull-up range computed earlier.
Slave mode in brief
A microcontroller can also act as an I2C slave, answering at its own address and holding SCL low (stretching) while its firmware prepares a reply. The slave sees an address match event, then bytes in or out, then a stop or repeated start. The same constraints as SPI slaves apply in spirit: the response to a read must be ready quickly, and handlers must be short, since a slow slave stretches the clock for every device on the bus. On the STM32F4 the slave uses the ADDR event, the TXE and RXNE events and the STOPF flag, which clears by reading SR1 and writing CR1. Design register maps for slave devices to be read in one transaction with auto-increment, so a master can fetch a whole status block with one address phase.
Testing the driver logic on a host
The sequencing logic above depends on hardware flags, but the layers above it, a device driver that builds register addresses and decodes bytes, are plain C that you can test without a board. Put the bus behind two function pointers, write(addr, buf, len) and read(addr, buf, len), and give the test a fake bus that holds a table of registers:
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
static uint8_t regs[256];
static uint8_t pointer;
static int fake_write(uint8_t addr7, const uint8_t *buf, uint32_t len)
{
(void)addr7;
if (len >= 1) pointer = buf[0]; /* first byte sets the register pointer */
for (uint32_t i = 1; i < len; i++) regs[pointer++] = buf[i];
return 0;
}
static int fake_read(uint8_t addr7, uint8_t *buf, uint32_t len)
{
(void)addr7;
for (uint32_t i = 0; i < len; i++) buf[i] = regs[pointer++]; /* auto-increment */
return 0;
}
static int16_t read_accel_x(void)
{
uint8_t reg = 0x3B, raw[2];
fake_write(0x68, ®, 1);
fake_read(0x68, raw, 2);
return (int16_t)((raw[0] << 8) | raw[1]); /* high byte first */
}
int main(void)
{
regs[0x3B] = 0xFF; regs[0x3C] = 0x38; /* -200 as big-endian 0xFF38 */
int16_t x = read_accel_x();
printf("accel x = %d\n", x);
assert(x == -200);
return 0;
}accel x = -200The test pins down the two details that most often go wrong in sensor drivers: the register pointer is set by a write before the read, and the two bytes combine in the right order with sign extension. A reversed byte order would print 14591 instead. The same fake bus can inject failures, returning a NACK on the third call, to check that the retry and recovery code behaves.
Choosing and verifying the clock speed
Start every new board at 100 kHz, prove the scan and the identity register reads work and only then raise the speed. At 400 kHz, check the rise time on the scope: from 30 percent to 70 percent of the supply it must be under 300 ns. A bus that works at 100 kHz and fails at 400 kHz almost always has a rise time problem, not a software problem. Measure the rise time directly with an oscilloscope probe at the farthest device: the pull-up is a resistor and the capacitance includes the scope probe itself, usually about 10 pF, so measure with a 10x probe and subtract expectations accordingly.
The actual SCL frequency also differs from the target because the peripheral derives it from the bus clock with an integer divider. In the F4 example the clock is 42 MHz / (3 * 35) = 400 kHz exactly, but a different bus clock gives a rounded result. Compute the real value from the register settings, and for devices with a hard maximum make sure rounding goes down, not up. When a design needs margin, choose 300 kHz or 350 kHz rather than the full 400 kHz, which gives the pull-ups and cabling some slack at the cost of a 20 percent longer transaction.
What changes on newer STM32 I2C peripherals
The sequence in this guide belongs to the older STM32 I2C block, found on the F1, F2, F4 and L1 families, which makes software walk through each event. Families from the F0, F3, F7, L0, L4, G0, G4 and H7 onward use a redesigned peripheral. It has a TIMINGR register that packs the prescaler, the data setup and hold times and the high and low clock periods into one value that the reference manual's timing tool or the CubeMX clock configuration computes for you, and a transfer is started by programming the slave address, the byte count and the direction in CR2 and setting START, after which the hardware sends the address, handles the repeated start and the stop and reports completion through ISR flags. The result is far less software sequencing and a much lower chance of the lock-ups that plague the older block, but the idea underneath, open-drain lines, addresses, ACK and recovery by clocking SCL, is identical. Learn the protocol from the wire first, and the peripheral differences become details you look up in one chapter of the reference manual.
When I2C is the wrong choice
I2C fails the engineer who needs speed: it moves at most about 44,000 bytes per second at 400 kHz, so a display of any size or a sensor sampled at tens of kilohertz belongs on SPI. It fails the one who needs noise immunity over distance: the open-drain lines and weak pull-ups pick up noise on a cable of more than a meter or two, and a differential bus such as RS-485 or CAN suits those runs. It fails designs with strict real-time needs on a shared bus, since a slow device can stretch the clock for milliseconds. And it requires care with 5 V and 3.3 V mixing: an I2C bus can be level-shifted with a simple MOSFET circuit, but the pull-ups on both sides must be sized for it.


