I2C (Inter-Integrated Circuit) is a two-wire serial bus that lets one controller talk to many chips on the same board, such as sensors, displays and small memories. Many sensors in Robotic Sensors use it.

Two Shared Wires

What each line does:

  • SDA carries the data, in both directions
  • SCL carries the clock, normally driven by the controller
  • both lines are open-drain: a device can only pull a line low, and a pull-up resistor pulls it high when nobody pulls it down
  • so two devices can never fight (one driving high while another drives low), which is why many devices can share the same two wires safely

One Transaction

Order of events on the bus:

  • START: SDA falls while SCL is high
  • the controller sends a 7-bit address plus one read or write bit
  • the target with that address answers with an ACK (it pulls SDA low for one clock)
  • data bytes follow, each one followed by an ACK
  • STOP: SDA rises while SCL is high

Timing rule:

  • data on SDA may only change while SCL is low, and must be stable while SCL is high
  • that is why a change of SDA while SCL is high can mean START or STOP

Addresses and speeds:

  • 7 bits give 128 addresses, and 16 are reserved, so about 112 devices can share one bus
  • standard mode 100 kHz, fast mode 400 kHz, fast mode plus 1 MHz

Clock Stretching

How it works:

  • a slow target can hold SCL low after the controller releases it, which means "wait, I am not ready yet"
  • the controller must check that SCL really went high before it sends the next bit

What goes wrong:

  • some I2C controllers do not handle stretching properly, and the Raspberry Pi's hardware I2C is a well-known example
  • the controller then samples SDA in the middle of a change, so bytes come back wrong or the device seems not to answer at all

Fixes:

  • lower the bus speed, so the stretch fits inside a normal clock period
  • use another interface on the sensor if it has one (UART or SPI)
  • use software I2C (bit-banging): the processor toggles two GPIO pins itself and waits for SCL to rise, so it always honours the stretch

Compared With SPI And UART

BusWiresClockAddressingTypical speed
I2C2 (SDA, SCL)shared, from the controller7-bit address in each message100 kHz to 1 MHz
SPI4 (SCLK, MOSI, MISO, one chip select per device)shared, from the controllera chip select line per deviceseveral to tens of MHz
UART2 (TX, RX)none, both sides agree on a baud ratenone, point to point9600 baud to a few Mbaud

When to use which:

  • I2C: many slow devices with few pins
  • SPI: fast data, for example a display or an ADC
  • UART: a simple link between two devices, for example a GPS module or a debug console