Bird
0
0
Raspberry Piprogramming~5 mins

Multiple I2C devices on same bus in Raspberry Pi

Choose your learning style9 modes available
Introduction

Using multiple I2C devices on the same bus lets you connect many sensors or modules to one Raspberry Pi without extra wires.

You want to read temperature from one sensor and humidity from another using I2C.
You have several small devices like displays and sensors that use I2C and want to connect them all.
You want to save GPIO pins by sharing the same two I2C wires for multiple devices.
You are building a project with many I2C modules and want to keep wiring simple.
Syntax
Raspberry Pi
import smbus

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

# To talk to a device, use its unique address
DEVICE_ADDRESS_1 = 0x40
DEVICE_ADDRESS_2 = 0x41

# Read or write data by specifying the device address
bus.write_byte(DEVICE_ADDRESS_1, 0x00)
data = bus.read_byte(DEVICE_ADDRESS_2)

Each I2C device must have a unique address on the bus.

Use the same bus object to communicate with all devices on that bus.

Examples
Control two LED devices with different addresses on the same I2C bus.
Raspberry Pi
DEVICE_ADDRESS_1 = 0x20
DEVICE_ADDRESS_2 = 0x21

bus.write_byte(DEVICE_ADDRESS_1, 0xFF)  # Turn on all LEDs on device 1
bus.write_byte(DEVICE_ADDRESS_2, 0x00)  # Turn off all LEDs on device 2
Read temperature and humidity from two sensors on the same bus.
Raspberry Pi
temperature_address = 0x48
humidity_address = 0x40

temp = bus.read_byte_data(temperature_address, 0x00)
hum = bus.read_byte_data(humidity_address, 0x01)
Sample Program

This program reads raw data from two I2C sensors with different addresses on the same bus every 2 seconds.

Raspberry Pi
import smbus
import time

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

# Example device addresses (replace with your devices')
TEMP_SENSOR_ADDR = 0x48
HUM_SENSOR_ADDR = 0x40

while True:
    # Read temperature data
    temp_raw = bus.read_byte_data(TEMP_SENSOR_ADDR, 0x00)
    # Read humidity data
    hum_raw = bus.read_byte_data(HUM_SENSOR_ADDR, 0x01)

    print(f"Temperature raw data: {temp_raw}")
    print(f"Humidity raw data: {hum_raw}")

    time.sleep(2)
OutputSuccess
Important Notes

Make sure each device has a unique I2C address to avoid conflicts.

Use the i2cdetect command on Raspberry Pi terminal to find device addresses.

Pull-up resistors are usually needed on the SDA and SCL lines for proper I2C communication.

Summary

You can connect many I2C devices on the same two wires if each has a unique address.

Use the same bus object to talk to all devices by specifying their addresses.

Check addresses with i2cdetect and ensure proper wiring with pull-up resistors.