Bird
0
0
Raspberry Piprogramming~30 mins

Multiple I2C devices on same bus in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
Multiple I2C Devices on Same Bus
📖 Scenario: You have a Raspberry Pi connected to two I2C sensors on the same bus. You want to read data from both sensors without conflicts.
🎯 Goal: Write a Python program that communicates with two I2C devices on the same bus by specifying their addresses and reading data from each.
📋 What You'll Learn
Create a dictionary called devices with two I2C device addresses as keys and their names as values
Create a variable called bus_number and set it to 1 (the default I2C bus on Raspberry Pi)
Use a for loop with variables address and name to iterate over devices.items()
Inside the loop, create an SMBus object for bus_number and read a byte from each device address
Print the device name and the byte read in the format: Device {name} at address {address} returned {data}
💡 Why This Matters
🌍 Real World
Many projects use multiple sensors on the same I2C bus to save wiring and pins. This skill helps you manage multiple devices efficiently.
💼 Career
Understanding how to communicate with multiple I2C devices is important for embedded systems, IoT development, and hardware interfacing roles.
Progress0 / 4 steps
1
Create the I2C devices dictionary
Create a dictionary called devices with these exact entries: 0x40: 'Temperature Sensor' and 0x48: 'Light Sensor'
Raspberry Pi
Hint

Use curly braces {} to create a dictionary with keys as addresses and values as names.

2
Set the I2C bus number
Create a variable called bus_number and set it to 1, which is the default I2C bus on Raspberry Pi
Raspberry Pi
Hint

Just assign the number 1 to the variable bus_number.

3
Read data from each I2C device
Use a for loop with variables address and name to iterate over devices.items(). Inside the loop, create an SMBus object for bus_number and read a byte from each device address using read_byte(address). Store the result in a variable called data
Raspberry Pi
Hint

Use for address, name in devices.items(): to loop. Use with SMBus(bus_number) as bus: to open the bus. Then read a byte with bus.read_byte(address).

4
Print the data from each device
Inside the for loop, add a print statement to display the device name, address, and data in this exact format: Device {name} at address {address} returned {data}
Raspberry Pi
Hint

Use an f-string in the print statement: print(f"Device {name} at address {address} returned {data}").