Bird
0
0
Raspberry Piprogramming~30 mins

Reading sensor data over I2C in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
Reading sensor data over I2C
📖 Scenario: You have a Raspberry Pi connected to a temperature sensor via the I2C bus. You want to read the temperature data from the sensor and display it.
🎯 Goal: Build a Python program that reads temperature data from an I2C sensor and prints the temperature value.
📋 What You'll Learn
Use the smbus2 library to communicate over I2C
Read data from the sensor's I2C address 0x48
Read the temperature register at address 0x00
Convert the raw data to a temperature value in Celsius
Print the temperature value
💡 Why This Matters
🌍 Real World
Reading sensor data over I2C is common in home automation, weather stations, and robotics projects where Raspberry Pi collects environmental data.
💼 Career
Understanding I2C communication and sensor data reading is important for embedded systems developers, IoT engineers, and hardware interfacing roles.
Progress0 / 4 steps
1
Set up I2C bus and sensor address
Import the SMBus class from the smbus2 library. Create a variable called bus that opens I2C bus number 1. Create a variable called sensor_address and set it to 0x48.
Raspberry Pi
Hint

Use from smbus2 import SMBus to import. Then create bus = SMBus(1) for I2C bus 1. Set sensor_address = 0x48 as the sensor's I2C address.

2
Set the register address to read temperature
Create a variable called temp_register and set it to 0x00, which is the register address for temperature data on the sensor.
Raspberry Pi
Hint

The temperature register is usually at address 0x00. Create temp_register = 0x00.

3
Read raw temperature data from the sensor
Use the bus.read_word_data method with sensor_address and temp_register to read the raw temperature data. Store the result in a variable called raw_temp.
Raspberry Pi
Hint

Use raw_temp = bus.read_word_data(sensor_address, temp_register) to read the raw data.

4
Convert raw data and print temperature
Convert the raw_temp value to Celsius by swapping bytes and dividing by 256. Store the result in temperature_celsius. Then print the temperature with print(f"Temperature: {temperature_celsius:.2f} °C").
Raspberry Pi
Hint

The sensor sends data in little endian, so swap bytes first. Then divide by 256 to get Celsius. Finally, print with print(f"Temperature: {temperature_celsius:.2f} °C").