Bird
0
0
Raspberry Piprogramming~5 mins

Writing commands to I2C device in Raspberry Pi

Choose your learning style9 modes available
Introduction

We write commands to I2C devices to control them or send data. This helps the Raspberry Pi talk to sensors, displays, or other hardware.

You want to turn on or off a sensor connected via I2C.
You need to send configuration settings to an I2C display.
You want to start a measurement on an I2C temperature sensor.
You need to control a motor driver connected through I2C.
You want to update data on an I2C EEPROM memory chip.
Syntax
Raspberry Pi
import smbus2

bus = smbus2.SMBus(bus_number)

device_address = 0xXX  # Replace XX with your device's I2C address
command = 0xYY         # Command or register to write
value = 0xZZ           # Data to send

bus.write_byte_data(device_address, command, value)

bus.close()

bus_number is usually 1 on Raspberry Pi models.

device_address is the I2C address of your device in hex.

Examples
This sends the value 0xFF to register 0x01 of the device at address 0x20.
Raspberry Pi
import smbus2

bus = smbus2.SMBus(1)
device_address = 0x20
command = 0x01
value = 0xFF
bus.write_byte_data(device_address, command, value)
bus.close()
This might turn off an OLED display by sending 0xAE to command 0x00.
Raspberry Pi
import smbus2

bus = smbus2.SMBus(1)
device_address = 0x3C
command = 0x00
value = 0xAE
bus.write_byte_data(device_address, command, value)
bus.close()
Sample Program

This program sends a command to start a temperature measurement on a sensor at address 0x48. It opens the I2C bus, writes the command and value, then closes the bus.

Raspberry Pi
import smbus2
import time

# Open I2C bus 1
bus = smbus2.SMBus(1)

# Device address (example: 0x48 for a temperature sensor)
device_address = 0x48

# Command/register to start temperature measurement
command = 0x01

# Value to write (example: 0x60 to start conversion)
value = 0x60

print(f"Sending command 0x{command:X} with value 0x{value:X} to device at 0x{device_address:X}")

# Write the command and value to the device
bus.write_byte_data(device_address, command, value)

print("Command sent successfully.")

# Close the bus
bus.close()
OutputSuccess
Important Notes

Always close the I2C bus after communication to free resources.

Check your device datasheet for correct command and value codes.

If you get an error, verify the device address and that the device is connected properly.

Summary

Use smbus2 library to write commands to I2C devices on Raspberry Pi.

Open the bus, send command and data with write_byte_data, then close the bus.

Commands control the device behavior or send data to it.