Scan for I2C Devices
Scan for I2C Devices
This tutorial shows how to create an I2C scanner using the NEXTuino BASE to detect the addresses of I2C devices connected to the board.
Prerequisites
- Arduino IDE installed
- NEXTuino BASE board
Example Code
The complete example is available on GitHub:
i2c_scanner.ino
Step-by-Step Guide
Step 1: Setup the Arduino Environment
- Connect your MICRO to your computer.
- Open the Arduino IDE.
- Ensure the appropriate board and port are selected in the Tools menu.
Step 2: Understanding the Code
Setup Function
void setup()
{
Wire.setSDA(PIN_WIRE0_SDA);
Wire.setSCL(PIN_WIRE0_SCL);
Wire.begin();
Serial.begin(9600);
while (!Serial);
Serial.println("\nI2C Scanner");
}
Wire.setSDA()/Wire.setSCL(): Sets the SDA and SCL pins for I2C communication.Wire.begin(): Initializes the I2C bus.Serial.begin(9600): Starts serial communication at 9600 baud.
Loop Function
void loop()
{
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for (address = 1; address < 127; address++)
{
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
// Device found at this address
}
else if (error == 4)
{
// Unknown error at this address
}
}
delay(5000); // Wait before next scan
}
- Scans I2C addresses 1 through 126.
Wire.beginTransmission(address): Attempts to contact a device at the given address.Wire.endTransmission()returns0if a device is found,4for an unknown error.
Step 3: Hardware Setup
- Connect your I2C device(s) to the NEXTuino BASE SDA and SCL pins.
- Ensure proper power and ground connections.
Step 4: Using the Scanner
- Open the Serial Monitor in the Arduino IDE.
- Set the baud rate to 9600.
- Observe the output — detected I2C device addresses are listed in hexadecimal.
Interpreting Results
- Addresses are shown in hex format (e.g.,
0x68). - Note down the addresses for use in your I2C-based projects.