Adafruit PureIO

1.1.11 · active · verified Fri Apr 17

Adafruit PureIO provides pure Python (i.e., no native extensions) access to Linux IO, specifically for I2C and SPI buses. It serves as a drop-in replacement for the `smbus` and `spidev` modules, making it suitable for embedded systems like Raspberry Pi without requiring compilation. The library is actively maintained by Adafruit, with releases typically focusing on infrastructure updates, bug fixes, and compatibility improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize an I2C bus using `SMBus` and perform a basic byte read operation. It includes error handling for common issues like bus not found or permission denied. Remember to enable I2C via your system configuration (e.g., `raspi-config` on Raspberry Pi) and ensure the user running the script has appropriate permissions (e.g., belongs to the 'i2c' group).

import os
from Adafruit_PureIO.smbus import SMBus

# Most Raspberry Pi boards use I2C bus 1
# On some older devices or specific setups, it might be bus 0
bus_id = int(os.environ.get('I2C_BUS_ID', '1'))
device_address = int(os.environ.get('I2C_DEVICE_ADDRESS', '0x50'), 16) # Example: EEPROM
register_address = int(os.environ.get('I2C_REGISTER_ADDRESS', '0x00'), 16)

try:
    with SMBus(bus_id) as bus:
        # Read a single byte from a device at device_address, register register_address
        data = bus.read_byte_data(device_address, register_address)
        print(f"Successfully read byte 0x{data:02X} from I2C bus {bus_id}, device 0x{device_address:02X}, register 0x{register_address:02X}.")
        
        # Example: Write a byte of data
        # bus.write_byte_data(device_address, register_address, 0x12)
        # print("Wrote 0x12 to device.")

except FileNotFoundError:
    print(f"Error: I2C bus /dev/i2c-{bus_id} not found. Is I2C enabled? (e.g., via raspi-config)")
except PermissionError:
    print(f"Error: Permission denied for /dev/i2c-{bus_id}. Are you in the 'i2c' group or running with sudo?")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →