scanner-i2c.ino

Arduino Mega 2560 (Rev3) · 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 Mega 2560 (ATmega2560, 16 MHz, 5 V): 54 digital I/O, 15 PWM, 16 analog inputs, 4 hardware UARTs. 1 or more I2C modules (e.g. PCF8574 LCD, MPU6050, BME280).

Wiring

SDA to pin SDA (20), SCL to SCL (21), 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 Mega 2560 » and the port, then Upload. PWM on 2-13 and 44-46; UART1=18/19, UART2=16/17, UART3=14/15; SPI on 50-53.

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 (20), SCL=SCL (21)) 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