Reading data from an I2C sensor lets your Arduino get information like temperature or light levels from other devices easily.
0
0
Reading I2C sensor data in Arduino
Introduction
You want to measure temperature using a sensor connected via I2C.
You need to read data from a digital compass or accelerometer.
You want to get sensor data without using many wires.
You are building a project that needs multiple sensors sharing the same two wires.
Syntax
Arduino
Wire.begin();
Wire.beginTransmission(address);
Wire.write(register);
Wire.endTransmission();
Wire.requestFrom(address, numberOfBytes);
while(Wire.available()) {
data = Wire.read();
}Wire.begin() starts the I2C communication.
You send the sensor's address and the register you want to read, then ask for data.
Examples
This reads 2 bytes from sensor at address 0x40 starting at register 0x00.
Arduino
Wire.begin(); Wire.beginTransmission(0x40); Wire.write(0x00); Wire.endTransmission(); Wire.requestFrom(0x40, 2); while(Wire.available()) { byte data = Wire.read(); }
This requests 6 bytes from device at 0x68 without specifying register first.
Arduino
Wire.begin(); Wire.requestFrom(0x68, 6); while(Wire.available()) { byte data = Wire.read(); }
Sample Program
This program reads 2 bytes from an I2C sensor at address 0x40 every second and prints the combined value to the Serial Monitor.
Arduino
#include <Wire.h> const int sensorAddress = 0x40; // Example sensor I2C address void setup() { Serial.begin(9600); Wire.begin(); } void loop() { Wire.beginTransmission(sensorAddress); Wire.write(0x00); // Register to read from Wire.endTransmission(); Wire.requestFrom(sensorAddress, 2); // Request 2 bytes if (Wire.available() == 2) { byte msb = Wire.read(); byte lsb = Wire.read(); int value = (msb << 8) | lsb; Serial.print("Sensor value: "); Serial.println(value); } else { Serial.println("No data received"); } delay(1000); // Wait 1 second before next read }
OutputSuccess
Important Notes
Always check if the sensor sends the expected number of bytes before reading.
Use the correct I2C address for your sensor; check its datasheet.
Use pull-up resistors on SDA and SCL lines if your board or sensor does not have them built-in.
Summary
I2C uses two wires to communicate with sensors.
Start communication with Wire.begin(), send address and register, then request data.
Read bytes carefully and combine them if needed to get sensor values.
