I2C
Addressing, repeated start, clock stretching and bus recovery.
Two wires, many chips
I2C (inter-integrated circuit) connects a controller to many peripheral chips (sensors, EEPROMs, port expanders, power-management ICs) using two shared open-drain lines:
- SCL: clock, driven by the controller
- SDA: data, driven by whoever is sending
Both lines need pull-up resistors; devices only ever pull low. Standard speeds are 100 kHz (standard), 400 kHz (fast), 1 MHz (fast-plus).
A transaction
S | ADDR(7) | W | A | REG | A | Sr | ADDR(7) | R | A | DATA | A | DATA | N | P
- S (start): SDA falls while SCL is high. Every transaction begins with one.
- Address and R/W bit: 7-bit address plus 1 direction bit (0 = write, 1 = read).
- A (ACK): the receiver pulls SDA low during the ninth clock. N (NACK): it leaves SDA high.
- Sr (repeated start): a start without a stop first, so the controller keeps the bus while switching direction.
- P (stop): SDA rises while SCL is high.
Data changes only while SCL is low; SDA transitions while SCL is high are reserved for start and stop.
Addresses
Most devices have a 7-bit address, often with a pin or two to select between a few values so several identical chips can share a bus. The address byte on the wire is (addr << 1) | rw, which is why datasheets disagree: some quote 0x48 (7-bit), some 0x90/0x91 (8-bit with R/W). Many libraries want the 7-bit form.
#include <stdio.h>
#include <stdint.h>
int main(void) {
uint8_t addr7 = 0x48; /* e.g. a temperature sensor */
printf("7-bit address 0x%02X\n", addr7);
printf("write byte on the wire: 0x%02X\n", (uint8_t)(addr7 << 1) | 0);
printf("read byte on the wire: 0x%02X\n", (uint8_t)(addr7 << 1) | 1);
return 0;
}
The register-read pattern
Most sensors are a set of registers. Reading one is a write of the register address followed by a read, joined by a repeated start:
- S, address + W, register number
- Sr, address + R, read N bytes (ACK each except the last, which gets a NACK)
- P
Using a stop instead of a repeated start in the middle also works with most devices, but another controller on a multi-controller bus could take the bus in between.
Clock stretching
A slow peripheral can hold SCL low after a byte to say "wait". The controller must notice SCL has not risen and pause. Most hardware I2C controllers handle this; bit-banged implementations must check SCL after releasing it. Some controllers (notably older Raspberry Pi hardware) handle stretching badly, so check if a device that stretches is unreliable.
Pull-up resistor sizing
The rise time of each line is set by the pull-up and the bus capacitance (all pins plus wiring, limited to 400 pF by the specification):
- Too large a resistor: slow rising edges, the bus fails at higher speeds.
- Too small: the devices cannot pull the line low enough (sink current limit, 3 mA in standard mode).
Typical values are 4.7 kΩ at 100 kHz and 2.2 kΩ at 400 kHz for short buses. Rise time is about 0.8473 × R × C; for 400 kHz it must be under 300 ns.
Errors and recovery
| Symptom | Likely cause |
|---|---|
| NACK on the address | Wrong address (7-bit versus 8-bit confusion), device not powered, device busy (EEPROM writing) |
| Bus stuck: SDA held low | A peripheral was interrupted mid-byte (controller reset during a read) and is still waiting to send a bit |
| Arbitration lost | Another controller is driving, or noise |
| Intermittent errors | Pull-ups too weak, too much capacitance, ground issues |
Bus recovery
The stuck-SDA case is common after a microcontroller reset during a transaction: the peripheral is still mid-byte holding SDA low, and the controller sees a busy bus forever. The standard fix, done at start-up:
- Configure SCL as a GPIO open-drain output and SDA as an input.
- Toggle SCL up to nine times, checking SDA after each pulse; stop once SDA is released.
- Generate a stop condition (SDA low to high while SCL is high).
- Reconfigure the pins for the I2C peripheral and reset it.
Every production I2C driver should do this.
Driver design
- Timeouts on every wait. A missing device or a stuck bus must not hang the firmware.
- One owner per bus. In an RTOS, protect the bus with a mutex; two tasks interleaving transactions corrupt both.
- Interrupt or DMA for long transfers. Polling a 400 kHz bus wastes about 22 µs per byte.
- Count errors per device. A rising NACK count is an early warning of a hardware fault.
Pitfall: EEPROMs NACK their address for several milliseconds after each page write while they program internally. Poll by sending the address until it ACKs ("acknowledge polling") rather than treating the NACK as a failure.
Interview question: After a microcontroller reset, the I2C bus is permanently busy with SDA low. Why, and how do you fix it?
Answer: The reset interrupted a read while a peripheral was driving a 0 bit; the peripheral keeps holding SDA low, waiting for clock pulses that will never come, so the controller sees a busy bus. Recover by switching SCL to GPIO and clocking it up to nine times until the peripheral releases SDA, then generating a stop condition and reinitialising the I2C peripheral. Do this at every start-up and after timeouts.
Interview question: Why does I2C use open-drain lines with pull-ups?
Answer: Several devices share the same two wires and any of them may need to drive a line low (data, ACK bits, clock stretching, multi-controller arbitration). With open-drain outputs, a device can only pull low or release, so two devices driving at once never short supply to ground; the line is low if anyone pulls it low (wired-AND). Pull-ups return the line high. The cost is rise time limited by the resistor and bus capacitance, which caps the speed.
Build it: keep the settings through a power cut
This is step 3 of the module project. Settings the technician changes on the service console (step 1), such as how hard a knock counts as a crash, must survive a flat battery. They live in a small I2C EEPROM.
Lab: Save and load settings in an I2C EEPROM
A 24C02 EEPROM (256 bytes) sits on I2C1 at address 0x50. The bus driver is already written (under Register map and definitions): eeprom_write, eeprom_read and eeprom_busy. You write the settings layer that the rest of the firmware uses.
The settings are stored as 6 bytes at EEPROM address 0x10:
| Byte | Contents |
|---|---|
| 0 | 0xA5, a marker that says "settings were saved here" |
| 1, 2 | crash_mg, low byte first |
| 3 | volume |
| 4 | flags |
| 5 | a checksum: 0 - (sum of bytes 0 to 4), so all six bytes add up to 0 (in 8 bits) |
settings_save(s)writes the 6 bytes in oneeeprom_write. The EEPROM then spends up to 5 ms storing them and ignores the bus meanwhile, so wait untileeprom_busy()returns false (at most 100 tries) before returning true. Return false if the write or the wait fails.settings_load(s)reads the 6 bytes back. If the read fails, the marker is wrong (a brand-new chip reads0xFFeverywhere) or the bytes do not add up to 0, fill in the defaults (crash_mg2500,volume3,flags0) and return false. Otherwise unpack them and return true.
Going deeper
Interview question: How would you share one I2C bus between a greenhouse controller's LCD and real-time clock reliably?
Answer: Check the addresses do not clash and the pull-ups suit the bus capacitance and speed, keep the wiring short, and give every transfer a timeout. If a device holds SDA low after a glitch, recover the bus by clocking SCL until it releases, then reinitialise. Report persistent errors instead of hanging.
Interview question: What is the difference between a stop and a repeated start in an I2C register read?
Answer: A register read writes the register address and then reads data. With a repeated start the controller goes straight from the write to the read without releasing the bus, so no other controller can take the bus in between and some devices require it to keep the register pointer. With a stop then start, the bus is released between the two parts; most single-controller systems tolerate it, but it is not atomic.
Interview question: Why might I2C work at 100 kHz but fail at 400 kHz?
Answer: Usually rise time: with pull-up resistors too large for the bus capacitance, the lines do not rise fast enough within a shorter clock period (400 kHz allows 300 ns), so bits are misread. Fix with smaller pull-ups, shorter wires or fewer devices. Other causes are a device that does not support fast mode, clock stretching mishandled by the controller, or noise.
Explain it: In your own words, explain why the I2C bus can get stuck after a microcontroller reset and how to recover it.
Answer: If the microcontroller resets in the middle of reading from a device, that device may be partway through sending a byte and holding the data line low for a 0 bit, waiting for clock pulses that will never come. The controller then sees the data line permanently low and thinks the bus is busy. Recovery: take the clock pin as a plain GPIO and pulse it up to nine times until the device releases the data line, then generate a stop condition, and reinitialise the I2C peripheral; drivers do this at start-up.