पाठ 11 / 25

I2C with the Wire Library

Two wires, many devices, addresses and pull-ups.

Addresses and pull-ups

I2C uses two shared lines, SDA (data) and SCL (clock), plus ground. The controller addresses each device by a 7-bit address (often written like 0x3C or 0x76), so many sensors can share the bus as long as addresses differ; some modules let you change the address with a jumper. The lines are open-drain and need pull-up resistors (commonly a few kΩ); many breakout boards include them. On the Uno R3, SDA is A4 and SCL is A5 (also on dedicated header pins); on other boards check the pinout. I2C is slower than SPI (100 kHz and 400 kHz are common speeds) but needs few pins.

An I2C scanner

Lists responding addresses; a standard first step when wiring a new module.

#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin();                       // join the bus as controller
  Serial.println(F("Scanning..."));
  for (uint8_t addr = 1; addr < 127; addr++) {
    Wire.beginTransmission(addr);
    if (Wire.endTransmission() == 0) {  // 0 = device acknowledged
      Serial.print(F("Found device at 0x"));
      if (addr < 16) Serial.print('0');
      Serial.println(addr, HEX);
    }
  }
  Serial.println(F("Done."));
}

void loop() {}

Watch the voltage

A 3.3 V sensor on a 5 V Uno R3 bus may need a level shifter, depending on the module. Check both the sensor and the breakout board datasheets.

त्वरित जाँच: How does an I2C controller select which device to talk to?

  • Each device needs its own pair of wires
  • By pulling that device's chip-select pin low
  • By choosing a different baud rate
  • By sending the device's address on the shared bus
Answer

By sending the device's address on the shared bus — Addressing lets many devices share SDA and SCL.