ESP32 BASICS · LESSON 15
Reading Sensors over I2C
Wiring an I2C sensor, scanning the bus for its address, and pulling a first reading.
I2C is a two-wire bus that lets many sensors and chips share the same pair of connections, each identified by its own address. It's the most common way to add off-the-shelf sensors — temperature, pressure, motion — to an ESP32 project.
Finding a device's address
i2c_scan.ino
#include
void setup() {
Wire.begin(); // default SDA=21, SCL=22
Serial.begin(115200);
delay(200);
for (byte addr = 1; addr < 127; addr++) {
Wire.beginTransmission(addr);
if (Wire.endTransmission() == 0) {
Serial.print("Found device at 0x");
Serial.println(addr, HEX);
}
}
}
void loop() {
}
Reading a sensor
Once you know a sensor's address, most sensor libraries handle the register-level reads and writes for you — you call something like sensor.readTemperature() and the library takes care of the I2C conversation underneath.
KEY IDEA
A scanner sketch is the fastest way to confirm wiring is correct before blaming a sensor or a library.