Bird
0
0
Raspberry Piprogramming~5 mins

smbus2 library for I2C in Raspberry Pi

Choose your learning style9 modes available
Introduction

The smbus2 library helps your Raspberry Pi talk to other devices using the I2C communication method. It makes reading and writing data easy and clear.

When you want to read sensor data like temperature or light from an I2C device.
When you need to control small devices like displays or motors connected via I2C.
When you want to send commands to an I2C device to change its settings.
When you want to build a project that uses multiple devices communicating over I2C.
Syntax
Raspberry Pi
from smbus2 import SMBus

with SMBus(bus_number) as bus:
    # Read or write commands here
    data = bus.read_byte_data(device_address, register)
    bus.write_byte_data(device_address, register, value)

bus_number is usually 1 on Raspberry Pi models.

Use with SMBus(bus_number) as bus: to open and close the connection safely.

Examples
This reads one byte from register 0x00 of the device at address 0x48.
Raspberry Pi
from smbus2 import SMBus

with SMBus(1) as bus:
    device_address = 0x48
    register = 0x00
    value = bus.read_byte_data(device_address, register)
    print(f"Value read: {value}")
This writes the value 255 (0xFF) to register 0x01 of the device at address 0x40.
Raspberry Pi
from smbus2 import SMBus

with SMBus(1) as bus:
    device_address = 0x40
    register = 0x01
    bus.write_byte_data(device_address, register, 0xFF)
This reads 4 bytes starting from register 0x00 from the device at address 0x50.
Raspberry Pi
from smbus2 import SMBus

with SMBus(1) as bus:
    device_address = 0x50
    block = bus.read_i2c_block_data(device_address, 0x00, 4)
    print(f"Block data: {block}")
Sample Program

This program opens the I2C bus 1, reads one byte from register 0x00 of the device at address 0x48, and prints the value.

Raspberry Pi
from smbus2 import SMBus

# This example reads a byte from a device at address 0x48
# and prints the value.

def read_sensor():
    device_address = 0x48  # Example device address
    register = 0x00        # Register to read from
    with SMBus(1) as bus:
        value = bus.read_byte_data(device_address, register)
    print(f"Sensor value: {value}")

if __name__ == "__main__":
    read_sensor()
OutputSuccess
Important Notes

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

Check the device address with i2cdetect -y 1 before running your program.

Always use with SMBus() to avoid leaving the bus open.

Summary

smbus2 helps your Raspberry Pi communicate with I2C devices easily.

Use it to read and write bytes or blocks of data to device registers.

Always open the bus safely with with SMBus(bus_number) as bus:.