About Lesson
Finding I2C devices on an ESP32 is a great way to identify and troubleshoot connected peripherals. The I2C scanner is a sketch (program) that scans the I2C bus to detect devices. Here’s how you can find and use an I2C scanner on an ESP32:
Steps to Find and Use an I2C Scanner on ESP32
. Open the I2C Scanner Sketch
- Open the Arduino IDE.
- Go to
File
>Examples
>Wire
>Scanner
. This will open a sketch for scanning I2C devices.
Modify the Sketch for ESP32
The I2C scanner sketch should work out of the box for most boards, including the ESP32, but it’s a good idea to ensure you have the correct configuration. The default sketch should be fine, but here’s a basic version you can use:
C++
#include <Wire.h>
void setup() {
Serial.begin(115200);
Wire.begin();
Serial.println("\nI2C Scanner");
}
void loop() {
byte error, address;
int nDevices = 0;
Serial.println("Scanning...");
for (address = 1; address < 127; address++) {
// The address of an I2C device can be from 1 to 127
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0) {
Serial.print("I2C device found at address 0x");
if (address < 16) {
Serial.print("0");
}
Serial.print(address, HEX);
Serial.println(" !");
nDevices++;
}
else if (error == 4) {
Serial.print("Unknown error at address 0x");
if (address < 16) {
Serial.print("0");
}
Serial.println(address, HEX);
}
}
if (nDevices == 0) {
Serial.println("No I2C devices found.");
}
else {
Serial.println("Done.");
}
delay(5000); // Wait 5 seconds before the next scan
}
Upload the Sketch
- Connect your ESP32 to your computer via USB.
- Select the correct board and port in the Arduino IDE:
- Go to
Tools
>Board
and select your ESP32 board (e.g.,ESP32 Dev Module
). - Go to
Tools
>Port
and select the correct port.
- Go to
- Click the upload button (right arrow icon) to upload the sketch to your ESP32.
Open the Serial Monitor
- Once the upload is complete, open the Serial Monitor:
- Go to
Tools
>Serial Monitor
or pressCtrl+Shift+M
(orCmd+Shift+M
on macOS). - Set the baud rate to
115200
.
- Go to
View the Results
- The Serial Monitor will display the addresses of any I2C devices connected to your ESP32.
- It will show something like
C++
I2C Scanner
Scanning...
I2C device found at address 0x3C !
I2C device found at address 0x27 !
Done.