Bird
0
0
Raspberry Piprogramming~7 mins

Reading sensor data over I2C in Raspberry Pi

Choose your learning style9 modes available
Introduction

We use I2C to talk to sensors and get their data easily. It helps the Raspberry Pi read information like temperature or light from small devices.

When you want to read temperature from a sensor connected to your Raspberry Pi.
When you need to get data from a light sensor to adjust screen brightness automatically.
When building a weather station that collects data from multiple sensors.
When you want to control or read data from small devices like accelerometers or gyroscopes.
Syntax
Raspberry Pi
import smbus

bus = smbus.SMBus(1)  # Use I2C bus 1
sensor_address = 0x48  # Sensor I2C address
register = 0x00  # Register to read from

# Read a byte from the sensor
data = bus.read_byte_data(sensor_address, register)

bus = smbus.SMBus(1) opens the I2C bus number 1 on Raspberry Pi.

sensor_address is the unique address of your sensor on the I2C bus.

Examples
Reads one byte of data from register 0x00 of the sensor at address 0x48.
Raspberry Pi
data = bus.read_byte_data(0x48, 0x00)
Reads two bytes (a word) from register 0x01 of the sensor.
Raspberry Pi
data = bus.read_word_data(0x48, 0x01)
Writes the value 0x60 to register 0x01 of the sensor to configure it.
Raspberry Pi
bus.write_byte_data(0x48, 0x01, 0x60)
Sample Program

This program reads temperature data from a TMP102 sensor connected via I2C. It reads raw data, adjusts byte order, converts it to Celsius, and prints it every 2 seconds.

Raspberry Pi
import smbus
import time

# Initialize I2C bus
bus = smbus.SMBus(1)

# Sensor I2C address (example: TMP102 temperature sensor)
sensor_address = 0x48

# Register to read temperature data
temp_register = 0x00

while True:
    # Read two bytes from temperature register
    raw = bus.read_word_data(sensor_address, temp_register)

    # Swap bytes because sensor sends data in big endian
    swapped = ((raw << 8) & 0xFF00) + (raw >> 8)

    # Convert to temperature (TMP102 specific formula)
    temp_c = (swapped >> 4) * 0.0625

    print(f"Temperature: {temp_c:.2f} °C")
    time.sleep(2)
OutputSuccess
Important Notes

Make sure I2C is enabled on your Raspberry Pi using raspi-config.

Use the command i2cdetect -y 1 in terminal to find your sensor's address.

Different sensors may require different ways to convert raw data to meaningful values.

Summary

I2C lets Raspberry Pi talk to sensors using addresses and registers.

Use smbus library to read and write data over I2C.

Always check your sensor's datasheet for correct addresses and data formats.