Generic I2C Device

Note

This class is only supported on the EV3 at this time. It could be added to Powered Up hubs in a future release. If you’d like to see this happen, be sure to ask us on our support page.

../_images/sensor_rj12_bluegreen.png
class I2CDevice(port, address)

Generic or custom I2C device.

Parameters
  • port (Port) – Port to which the device is connected.

  • address (int) – I2C address of the client device. See I2C Addresses.

Example: Read and write to an I2C device

#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.iodevices import I2CDevice
from pybricks.parameters import Port

# Initialize the EV3
ev3 = EV3Brick()

# Initialize I2C Sensor
device = I2CDevice(Port.S2, 0xD2 >> 1)

# Read one byte from the device.
# For this device, we can read the Who Am I
# register (0x0F) for the expected value: 211.
if 211 not in device.read(0x0F):
    raise OSError("Device is not attached")

# To write data, create a bytes object of one
# or more bytes. For example:
# data = bytes((1, 2, 3))

# Write one byte (value 0x08) to register 0x22
device.write(0x22, bytes((0x08,)))

I2C Addresses

I2C addresses are 7-bit values. However, most vendors who make LEGO compatible sensors provide an 8-bit address in their documentation. To use those addresses, you must shift them by 1 bit. For example, if the documented address is 0xD2, you can do address = 0xD2 >> 1.

Advanced I2C Commands

Some rudimentary I2C devices do not require a register argument or even any data. You can achieve this behavior as shown in the examples below.

Example: Advanced I2C read and write techniques

#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.iodevices import I2CDevice
from pybricks.parameters import Port

# Initialize the EV3
ev3 = EV3Brick()

# Initialize I2C Sensor
device = I2CDevice(Port.S2, 0xD2 >> 1)

# Recommended for reading
result, = device.read(reg=0x0F, length=1)

# Read 1 byte from no particular register:
device.read(reg=None, length=1)

# Read 0 bytes from no particular register:
device.read(reg=None, length=0)

# I2C write operations consist of a register byte followed
# by a series of data bytes. Depending on your device, you
# can choose to skip the register or data as follows:

# Recommended for writing:
device.write(reg=0x22, data=b'\x08')

# Write 1 byte to no particular register:
device.write(reg=None, data=b'\x08')

# Write 0 bytes to a particular register:
device.write(reg=0x08, data=None)

# Write 0 bytes to no particular register:
device.write(reg=None, data=None)

Additional technical resources

The I2CDevice class methods call functions from the Linux SMBus driver. To find out which commands are called under the hood, check the Pybricks source code. More details about using I2C without MicroPython can be found on the ev3dev I2C page.