scanner-i2c.ino

Arduino Duemilanove — Board Fiche · File : scanner-i2c.ino · Language : Arduino · Use case : Détecter les périphériques I2C connectés et afficher leurs adresses

Before writing a driver, check that the module (sensor, display, expander) answers on the bus. Wire sweeps 127 addresses and lists the ones that ACK — the reflex move when a device « does not work ».

Hardware required

An Arduino Duemilanove (ATmega168 or 328P, 16 MHz, 5 V) with its mini-USB-B cable; the serial port appears once the FTDI driver is installed. 1 or more I2C modules (e.g. PCF8574 LCD, MPU6050, BME280).

Wiring

SDA to pin SDA (A4), SCL to SCL (A5), VCC 5 V (or 3.3 V) and GND; pull-up resistors are usually already fitted on modules.

How it works

beginTransmission/endTransmission returns 0 when a chip pulls SDA low (ACK): the address prints in hex. In the Arduino IDE, select « Arduino Duemilanove » (or « Diecimila » for very old boards) and the FTDI port, then Upload. The ATmega168 leaves only 14 KB for the sketch.

Going further

Note the found address and try the vendor library with it; 0x27 (LCD) and 0x3C (OLED) are the classics.

scanner-i2c.ino

// Scanner de bus I2C (SDA=SDA (A4), SCL=SCL (A5)) avec la bibliotheque Wire.
#include <Wire.h>

void setup() {
  Wire.begin();
  Serial.begin(9600);
  while (!Serial);
  Serial.println(F("Scanner I2C — 8 adresses par ligne"));
}

void loop() {
  int trouve = 0;
  for (byte addr = 1; addr < 127; addr++) {
    Wire.beginTransmission(addr);
    if (Wire.endTransmission() == 0) {
      Serial.print(F("Peripherique a 0x"));
      Serial.println(addr, HEX);
      trouve++;
    }
  }
  Serial.print(trouve);
  Serial.println(F(" peripherique(s) — nouvelle passe dans 5 s"));
  delay(5000);
}

← Back to the board