Skip to content
systemcoding.dev
Embedded

Scan for I2C Devices With the Arduino Wire Library

Write an Arduino I2C scanner with Wire.beginTransmission and endTransmission, read the error codes and fix the usual reasons a device does not appear.

7 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Arduino, Arm and C logos.

The first thing to do with any new I2C board is find out whether the devices on it answer. An I2C scanner does that in a few lines: it tries every address and records which ones acknowledge. The Arduino Wire library makes the scan simple, and reading its return codes correctly tells you more than "found" or "not found". This post writes a scanner for an Arduino Uno (ATmega328P, Arduino AVR core 1.8.6), explains the error codes returned by Wire.endTransmission, covers the clock speed and the 32-byte buffer, and then lists what to check when a device does not appear. The protocol behind the scan is in the posts on I2C addressing and the I2C guide in this cluster.

Wiring on an Uno

The hardware I2C pins of the ATmega328P are fixed. On an Uno R3, SDA is analog pin A4 and SCL is A5; they also appear on the two pins next to AREF labeled SDA and SCL. Connect each device's SDA to SDA, SCL to SCL, power and ground. Most breakout boards carry pull-up resistors; if yours does not, add 4.7 kilohm resistors from each line to 5 V (or 3.3 V for 3.3 V devices). The Uno enables the ATmega's internal pull-ups of around 20 to 50 kilohms when Wire.begin() is called, which is too weak to run a bus of any length reliably, so use external resistors.

A 3.3 V sensor on a 5 V Uno needs level shifting on SDA and SCL, or a 3.3 V board.

The simplest scanner

scanner.inocpp
#include <Wire.h>

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Serial.println(F("I2C scan"));
}

void loop()
{
  uint8_t found = 0;

  for (uint8_t address = 8; address < 120; address++) {
    Wire.beginTransmission(address);
    uint8_t error = Wire.endTransmission();

    if (error == 0) {
      Serial.print(F("device at 0x"));
      if (address < 16) Serial.print('0');
      Serial.println(address, HEX);
      found++;
    }
  }

  Serial.print(found);
  Serial.println(F(" device(s) found"));
  delay(5000);
}

Wire.beginTransmission(address) sets up a write to the 7-bit address, queueing no data. Wire.endTransmission() sends the START, the address byte with the write bit, and the STOP, and returns a status code. A return of 0 means the device acknowledged its address.

The loop runs from address 8 to 119 (0x08 to 0x77), the usable range, skipping the reserved ones. With an MPU-6050 at 0x68 and an SSD1306 OLED at 0x3C, the monitor shows:

Text
I2C scan
device at 0x3C
device at 0x68
2 device(s) found

What the return code means

Wire.endTransmission() returns a byte that classifies the result:

CodeMeaning
0Success: the transmission completed and the device acknowledged
1Data too long for the transmit buffer
2Received NACK on transmit of the address
3Received NACK on transmit of data
4Other error
5Timeout (on newer cores)

For a scan, only 0 and 2 matter in normal cases: 0 is a device, 2 is no device. Code 4 deserves attention, since it signals a bus fault such as a stuck line, and code 5 means the bus was blocked. A scanner that prints the unusual codes helps find a hung bus:

scanner_codes.inocpp
#include <Wire.h>

void setup()
{
  Serial.begin(115200);
  Wire.begin();
}

void loop()
{
  for (uint8_t address = 8; address < 120; address++) {
    Wire.beginTransmission(address);
    uint8_t error = Wire.endTransmission();

    if (error == 0) {
      Serial.print(F("found 0x"));
      Serial.println(address, HEX);
    } else if (error == 4) {
      Serial.print(F("bus error at 0x"));
      Serial.println(address, HEX);
    }
    // error 2 means nothing answered; stay quiet
  }
  Serial.println(F("--"));
  delay(3000);
}

If SDA is stuck low, every address returns code 4 or 5 (depending on the core) and the monitor fills with bus error lines, which is distinct from the clean "nothing found" of an empty bus.

Setting the clock speed

Wire.begin() starts the bus at 100 kHz. Wire.setClock(400000) raises it to 400 kHz for devices that support fast mode. The ATmega328P derives SCL from the CPU clock with TWBR and a prescaler, so at 16 MHz the formula is SCL = F_CPU / (16 + 2 * TWBR * prescaler). For 400 kHz, TWBR = 12 with prescaler 1 gives 16,000,000 / (16 + 24) = 400,000. For a scan, speed does not matter, but it is a good habit to scan at the speed the devices will run at, because a bus that works at 100 kHz and fails at 400 kHz shows up in the scan:

scan_speeds.inocpp
void scanAt(uint32_t hz)
{
  Wire.setClock(hz);
  uint8_t found = 0;
  for (uint8_t a = 8; a < 120; a++) {
    Wire.beginTransmission(a);
    if (Wire.endTransmission() == 0) found++;
  }
  Serial.print(hz);
  Serial.print(F(" Hz: "));
  Serial.print(found);
  Serial.println(F(" device(s)"));
}

void loop()
{
  scanAt(100000);
  scanAt(400000);
  delay(5000);
}
Text
100000 Hz: 2 device(s)
400000 Hz: 2 device(s)

If the 400 kHz line shows fewer devices than the 100 kHz line, the pull-ups are too weak or the wiring too long for fast mode. Strengthen the pull-ups or stay at 100 kHz.

Reading something from a found device

A scan proves presence; reading an identity register proves the device is the one you think it is. The Wire pattern for a register read is a write of the register address without a stop, then a request:

read_reg.inocpp
uint8_t readRegister(uint8_t address, uint8_t reg)
{
  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.endTransmission(false);                 // false: repeated start, keep the bus
  Wire.requestFrom(address, (uint8_t)1);
  return Wire.available() ? Wire.read() : 0xFF;
}

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  uint8_t id = readRegister(0x68, 0x75);       // MPU-6050 WHO_AM_I
  Serial.print(F("WHO_AM_I = 0x"));
  Serial.println(id, HEX);
}
Text
WHO_AM_I = 0x68

Wire.endTransmission(false) is the key detail: the argument false sends a repeated start instead of a stop, so the following requestFrom continues the same transaction. The default true sends a STOP, which breaks the read on devices that need the repeated start and on some that return the previous register's data. Wire.requestFrom(address, quantity) reads the number of bytes and returns how many arrived; Wire.available() and Wire.read() then deliver them.

The 32-byte buffer

The Wire library has a 32-byte buffer on AVR (BUFFER_LENGTH in Wire.h), including the address byte on the write side, so a single transmission can carry at most 31 data bytes and requestFrom returns at most 32. A write of more bytes returns error code 1. To write more, split the transmission into several, which also means several START and STOP conditions, so check that the device allows it (an EEPROM page write must not be split across a page boundary). Boards with larger RAM, such as the ESP32 or the SAMD21, use larger buffers; read the core's Wire.h.

When the device does not show up

Work through this list in order.

  1. Power and ground. Measure the supply at the device's pins. A device at the wrong voltage or with a missing ground does nothing.

  2. SDA and SCL swapped. Swapped lines look exactly like an absent device. Compare the breakout's silkscreen with the Uno's pins.

  3. Pull-ups. With the device disconnected, measure the voltage on SDA and SCL: both should sit at the supply. A line at 0 V is shorted or stuck; a line floating around mid-supply has no pull-up.

  4. Address. Scan the full range. If the device appears at an address other than the datasheet's, an address pin is wired differently, or the datasheet quotes the 8-bit form (see the I2C addressing post).

  5. Level mismatch. A 3.3 V device on 5 V lines may not respond, or be damaged, and a 1.8 V device needs a shifter.

  6. A device that must be woken up. Some sensors have an enable or chip-select line that must be asserted, or start in a sleep mode that ignores the address. Check the datasheet.

  7. Speed. Try Wire.setClock(10000) for a very marginal bus; if the device appears, the bus is too slow-edged for 100 kHz.

  8. A hung bus. If every address returns an error code 4, SDA or SCL is stuck. Power-cycle the board and the devices, and use the nine-clock recovery from the dedicated post if it recurs.

What a scan cannot tell you

A scan is a write of an address with no data, and a few devices react to that. Some EEPROMs interpret a lone address as the start of a write sequence, and some devices respond to addresses in reserved ranges. A scan also cannot distinguish two different devices with the same address, and a device that is busy (an EEPROM in its write cycle) NACKs its address and is missed. Scan twice if you suspect that.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.