Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Serial and Communication

The I2C Bus (Wire Library)

Connect many devices with two wires: how I2C addresses, SDA and SCL work, the Wire library, scanning for devices, reading registers, pull-ups and common problems.

Sensors, displays, real-time clocks and memory chips all need to talk to a microcontroller, and pins are limited. I2C (pronounced "I squared C", also written IยฒC or TWI) lets you connect dozens of devices to the same two wires. Each device has its own address, the Arduino is the controller (formerly "master"), and the devices are peripherals (formerly "slaves") that answer when called.

No I2C hardware is available on this site, so the Arduino code is read-only. The C programs are labelled stand-ins: they model addresses, bytes and a pretend bus so you can see what the Wire library is doing.

The two wires

  • SDA: serial data.
  • SCL: serial clock, driven by the controller.

Plus power and ground. On an Uno, SDA is A4 and SCL is A5 (also marked next to AREF on newer boards); other boards have dedicated pins labelled SDA and SCL. Both lines are open drain: devices only pull them low, and pull-up resistors (usually 4.7 kilohms to the supply) pull them high again. Most breakout modules already include pull-ups, so you only add them for bare chips or long buses with many boards.

Standard speed is 100 kHz; fast mode is 400 kHz (Wire.setClock(400000)). Voltage levels matter: a 3.3 V sensor on a 5 V bus needs a level shifter, though many modules include one.

Addresses and transactions

Every device has a 7-bit address (0x08 to 0x77 are usable). For example, the common PCF8574 LCD backpack uses 0x27 or 0x3F, the DS3231 clock 0x68, the BMP280 pressure sensor 0x76 or 0x77, and a typical OLED 0x3C. Two devices with the same address on one bus conflict; many chips have address pins or solder jumpers to change it.

A transaction starts with the controller sending the address plus a read/write bit. The device that recognizes its address answers with an acknowledge (ACK).

sequenceDiagram
  participant C as Controller (Arduino)
  participant P as Peripheral 0x68
  C->>P: START + address 0x68 + Write
  P-->>C: ACK
  C->>P: register number
  P-->>C: ACK
  C->>P: REPEATED START + address 0x68 + Read
  P-->>C: ACK
  P-->>C: data byte
  C->>P: NACK + STOP

Reading a register: first write which register you want, then read it.

The Wire library

Wire is built in. To write bytes to a device:

C++
#include <Wire.h>

void setup() {
  Wire.begin();                       // join the bus as controller
  Wire.beginTransmission(0x68);       // address the device
  Wire.write(0x00);                   // register number
  Wire.write(0x2A);                   // value
  byte status = Wire.endTransmission();  // 0 = success
}

void loop() { }

endTransmission() actually sends the data and returns a status: 0 success, 2 address not acknowledged, 3 data not acknowledged, 4 other error. Always check it; code that ignores it keeps "working" with a disconnected device.

To read a register:

C++
byte readRegister(byte address, byte reg) {
  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.endTransmission(false);        // false = keep control (repeated start)
  Wire.requestFrom(address, (byte)1);
  if (Wire.available()) {
    return Wire.read();
  }
  return 0xFF;
}

Scanning the bus

If a device does not respond, the first step is a scanner: try every address and see who acknowledges.

C++
#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin();
  for (byte address = 1; address < 127; address++) {
    Wire.beginTransmission(address);
    if (Wire.endTransmission() == 0) {
      Serial.print("Found device at 0x");
      Serial.println(address, HEX);
    }
  }
}

void loop() { }

Nothing found at all usually means wiring (swapped SDA and SCL, missing ground, no power) or missing pull-ups. A device at an unexpected address often means a jumper setting.

C Stand-in: a pretend I2C bus scan (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: addresses on the wire

Under the hood the first byte of every transaction is the 7-bit address shifted left by one, with the read/write flag in bit 0 (0 = write, 1 = read). Some datasheets quote the 8-bit write address (such as 0x4E) instead of the 7-bit address (0x27): the Wire library wants the 7-bit form.

C Stand-in: building the address byte (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Multi-byte values and endianness

Sensors often return 16-bit values as two bytes, high byte first. Combine them with a shift: value = (high << 8) | low. Signed readings need care: cast to int16_t so a value like 0xFFF6 becomes -10, not 65526.

C Stand-in: combining two bytes into a signed value (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

When I2C misbehaves

  • Nothing found: check SDA/SCL are not swapped, check power and ground, and confirm pull-ups exist.
  • Works for a while, then hangs: long wires or noise; lower the clock to 100 kHz and shorten cables (practical length is under about a meter).
  • Two devices clash: same address; change one with its jumper, or use a multiplexer such as the TCA9548A.
  • Reading garbage: wrong register or endianness, or voltage mismatch.
  • Sketch freezes: on a stuck bus. Newer cores allow Wire.setWireTimeout() to avoid waiting forever.

I2C is slower than SPI but uses fewer pins and scales better; it is the right choice for most low-speed sensors, and for displays described in LCD and OLED displays.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many signal wires does I2C use (not counting power and ground)?

    SDA carries data and SCL carries the clock; every device shares the same two lines.
  2. 2. What does Wire.endTransmission() returning 2 mean?

    0 is success; 2 means no device answered at that address, which usually points to wiring or a wrong address.
  3. 3. Why are pull-up resistors needed on SDA and SCL?

    The bus is open drain. Without pull-ups the lines would float and never reach a clean high level.
  4. 4. A datasheet quotes an 8-bit write address 0x4E. What should you pass to Wire?

    The Wire library takes the 7-bit address, which is the 8-bit address shifted right by one: 0x4E >> 1 is 0x27.

Summary

  • I2C connects many devices over SDA and SCL; each has a unique 7-bit address.
  • Pull-up resistors are required; speeds are 100 kHz (standard) and 400 kHz (fast).
  • Wire.beginTransmission, write, endTransmission and requestFrom do the work; check the return status.
  • Scan the bus first when debugging, mind 7-bit versus 8-bit addresses and multi-byte values.

Next: The SPI Bus