0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Use I2C on Raspberry Pi: Setup and Example

To use I2C on Raspberry Pi, first enable the I2C interface via raspi-config or Raspberry Pi OS settings. Then, use Python with the smbus2 library to communicate with I2C devices by specifying the bus number and device address.
📐

Syntax

Using I2C on Raspberry Pi involves opening the I2C bus and communicating with devices by their addresses. The common Python syntax uses the smbus2 library:

  • bus = SMBus(bus_number): Opens the I2C bus (usually 1 on Raspberry Pi models after revision 2).
  • bus.read_byte_data(address, register): Reads a byte from a device register.
  • bus.write_byte_data(address, register, value): Writes a byte to a device register.
python
from smbus2 import SMBus

bus = SMBus(1)  # Open I2C bus 1
address = 0x20  # Device I2C address

# Read a byte from register 0x00
data = bus.read_byte_data(address, 0x00)

# Write a byte value 0xFF to register 0x01
bus.write_byte_data(address, 0x01, 0xFF)

bus.close()
💻

Example

This example shows how to read a byte from an I2C device at address 0x20 on bus 1 and print the value. It assumes the I2C interface is enabled and the device is connected properly.

python
from smbus2 import SMBus

bus = SMBus(1)  # Use I2C bus 1
address = 0x20  # Replace with your device's address
register = 0x00  # Register to read from

try:
    value = bus.read_byte_data(address, register)
    print(f"Read value: {value}")
finally:
    bus.close()
Output
Read value: 42
⚠️

Common Pitfalls

  • I2C not enabled: Forgetting to enable I2C in Raspberry Pi settings will cause errors.
  • Wrong bus number: Use bus 1 on most Raspberry Pi models; bus 0 is for older versions.
  • Incorrect device address: Use i2cdetect -y 1 to find connected device addresses.
  • Wiring mistakes: Ensure SDA and SCL pins are connected correctly with pull-up resistors if needed.
python
import smbus2

# Wrong bus number example (legacy bus 0)
try:
    bus = smbus2.SMBus(0)  # Usually incorrect on modern Pi
except FileNotFoundError:
    print("Bus 0 not found, use bus 1 instead.")

# Correct bus usage
bus = smbus2.SMBus(1)
bus.close()
Output
Bus 0 not found, use bus 1 instead.
📊

Quick Reference

Steps to use I2C on Raspberry Pi:

  • Enable I2C via sudo raspi-config > Interface Options > I2C.
  • Install Python library: pip install smbus2.
  • Connect device to SDA (GPIO 2) and SCL (GPIO 3) pins.
  • Use i2cdetect -y 1 to find device addresses.
  • Write Python code to read/write using smbus2.

Key Takeaways

Enable I2C interface on Raspberry Pi before using it.
Use bus number 1 for I2C communication on most Raspberry Pi models.
Check connected device addresses with i2cdetect tool.
Use the smbus2 Python library for easy I2C read/write operations.
Double-check wiring and device addresses to avoid communication errors.