Skip to content
Tactiverge

I2C: many devices on two wires

How I2C lets one microcontroller talk to many sensors over a shared two-wire bus: addresses, open-drain lines and pull-ups, acknowledgements, and reading a register.

Lesson 2 of 6 · 30 min · Self-paced · Free

Many sensors, few pins

A small robot might have a motion sensor, a temperature sensor, a distance sensor and a little display. Giving each one its own UART would use up a microcontroller's pins quickly. I2C (pronounced "I-squared-C", short for inter-integrated circuit) solves this: many devices share the same two wires, and each has an address.

I2C is everywhere in hobby and professional electronics, especially for sensors. Understanding how it works will help you read datasheets and, more often, work out why a sensor is not answering.

Two wires and a controller

The two signals are:

  • SCL (serial clock): generated by the controller, usually the microcontroller.
  • SDA (serial data): carries bits in both directions, one way at a time.

The other devices are called targets (older documents say master and slave; newer ones use controller and target). Unlike a UART, I2C is synchronous: the controller supplies a clock, so both sides know exactly when to read each bit and the clocks do not need to agree in advance. Common speeds are 100 kbit/s (standard mode) and 400 kbit/s (fast mode), with faster modes on some devices.

All devices also share ground and, usually, a supply voltage.

Open-drain lines and pull-up resistors

Here is the clever part that makes sharing safe. No device ever drives an I2C line high. Each device can only pull a line low (connect it to ground) or let go of it. A pull-up resistor on each line gently pulls it high whenever nobody is pulling it low. This is called an open-drain (or open-collector) connection.

Why bother? If two devices drove the same wire, one high and one low, they would fight, and a large current could flow between them. With open-drain lines, the worst case is that the line is low, which is harmless. It also lets any device hold the line low to signal something, which I2C uses for acknowledgements and for clock stretching, where a slow target holds SCL low to ask the controller to wait.

Pull-up values of a few kilohms are typical; many boards use something between 2.2 kΩ and 10 kΩ. Too large a resistance and the lines rise slowly, especially with long wires that add capacitance; too small and devices must sink more current when pulling low. Many sensor breakout boards already include pull-ups, and several boards on one bus put several resistors in parallel, so check what is fitted. Missing pull-ups are one of the most common reasons an I2C bus does nothing at all.

How a transfer works

Normally SDA changes only while SCL is low and stays steady while SCL is high. Two special patterns break that rule on purpose:

  • START: SDA falls while SCL is high. "Everyone listen, a transfer is beginning."
  • STOP: SDA rises while SCL is high. "The transfer is over; the bus is free."

After a START, the controller sends an address byte: the target's 7-bit address followed by one bit saying whether it wants to write (0) or read (1). Every byte on I2C is followed by a ninth clock pulse for the acknowledge bit: the receiver pulls SDA low (ACK) to say "got it", or leaves it high (NACK). If no device has that address, nobody pulls SDA low, the controller sees a NACK, and your code learns that the device is absent, unpowered or wired wrongly.

Address arithmetic

Suppose a sensor's datasheet gives the 7-bit address 0x48. (This is an example address for this lesson; always use the value in your own device's datasheet.) The address byte is the address shifted left by one bit, with the read/write bit in the lowest place:

write: (0x48 << 1) | 0 = 0x90
read:  (0x48 << 1) | 1 = 0x91

Some datasheets and libraries quote the 7-bit address (0x48), others the 8-bit byte (0x90). Mixing these up is a classic bug: if a device "should be at 0x90" but your library wants 7-bit addresses, use 0x48.

Reading a register

Most I2C sensors present their data as numbered registers, like small mailboxes inside the chip. One register might hold a measurement, another a configuration setting. Reading a register usually goes like this:

  1. START, then the address byte with write (0x90 in our example). Target ACKs.
  2. Send the register number you want. Target ACKs.
  3. Repeated START (a START without a STOP first, so no other controller can grab the bus), then the address byte with read (0x91). Target ACKs.
  4. The target sends data bytes. The controller ACKs each one except the last, which it NACKs to say "that's enough".
  5. STOP.

In firmware you rarely toggle the pins yourself; your board's library provides a function for the whole sequence. The code below uses a generic stand-in called i2c_write_read. Its name and arguments are illustrative, not from any particular library, and the device, address and register are made up for this lesson.

#include <stdint.h>

/* Stand-in for your board's I2C library: write wlen bytes, then a repeated
   start, then read rlen bytes. Returns 0 on success, nonzero on NACK/error. */
int i2c_write_read(uint8_t addr7, const uint8_t *wbuf, int wlen, uint8_t *rbuf, int rlen);

#define EXAMPLE_SENSOR_ADDR  0x48   /* example address only: check your datasheet */
#define EXAMPLE_TEMP_REG     0x05   /* made-up register for this lesson          */

/* Reads temperature in hundredths of a degree. Returns 0 on success. */
int read_temperature_cdeg(int16_t *out)
{
    uint8_t reg = EXAMPLE_TEMP_REG;
    uint8_t buf[2];
    if (i2c_write_read(EXAMPLE_SENSOR_ADDR, &reg, 1, buf, 2) != 0) {
        return -1;                       /* no ACK: wrong address, wiring, power */
    }
    *out = (int16_t)(((uint16_t)buf[0] << 8) | buf[1]);   /* high byte first */
    return 0;
}

Suppose our made-up sensor stores temperature as a signed 16-bit number in hundredths of a degree, high byte first. If the two bytes are 0x09 and 0xC4, the value is 0x09C4 = 2500, meaning 25.00 °C. If they are 0xFE and 0x0C, the 16-bit pattern 0xFE0C read as a signed two's-complement number is −500, meaning −5.00 °C. The byte order, signedness and scaling all come from the datasheet, and getting any one wrong produces plausible-looking nonsense. Notice that the function returns an error code: as the reliable-pipelines lesson argued, a failed read must never quietly become a temperature.

How long does it take?

Each byte costs 9 clock pulses (8 bits plus ACK). The register read above moves 5 bytes (address, register, address, two data bytes), about 45 clock pulses, plus START and STOP. At 100 kHz that is about 450 µs; at 400 kHz about 112.5 µs. Fast enough for a few hundred readings per second from a handful of sensors, but not for streaming large amounts of data.

Common problems

  • Address conflicts: two identical sensors share the same address. Many devices offer an address-select pin to change one or two address bits; otherwise you need separate buses or a multiplexer chip.
  • A stuck bus: if the controller resets in the middle of a transfer, a target may be left holding SDA low. Firmware often recovers by toggling SCL several times until SDA is released.
  • Long wires: I2C was designed for connections on a single circuit board. Over long cables, capacitance slows the edges and noise creeps in.
  • Scanning: a simple diagnostic is to try every address and list those that ACK. If your sensor does not appear, check power, ground, pull-ups and wiring before touching your code.

Knowledge check

Check your understanding

  1. 1. A target's 7-bit address is 0x3C. What address byte does the controller send to read from it?
  2. 2. Why do I2C lines need pull-up resistors?
  3. 3. After sending an address byte, the controller sees a NACK. What does this most likely mean?
  4. 4. A sensor returns the bytes 0xFF and 0x9C, high byte first, as a signed 16-bit value in hundredths of a degree. What temperature is this?
  5. 5. Why does a register read use a repeated START instead of a STOP followed by a new START?

Go further