class I2C – a two-wire serial protocol

I2C is a two-wire protocol for communicating between devices. At the physical level it consists of 2 wires: SCL and SDA, the clock and data lines respectively.

I2C objects are created attached to a specific bus. They can be initialised when created, or initialised later on.

Printing the i2c object gives you information about its configuration.

The basic methods are send and recv:

i2c.send('abc')      # send 3 bytes
i2c.send(0x42)       # send a single byte, given by the number
data = i2c.recv(3)   # receive 3 bytes

To receive inplace, first create a bytearray:

data = bytearray(3)  # create a buffer
i2c.recv(data)       # receive 3 bytes, writing them into data

A master must specify the recipient’s address:

i2c.init(I2C.MASTER)
i2c.send('123', 0x42)        # send 3 bytes to slave with address 0x42
i2c.send(b'456', addr=0x42)  # keyword for address

Constructors

Methods

i2c.deinit()

Turn off the I2C bus.

i2c.is_ready(addr)

Check if an I2C device responds to the given address. Only valid when in master mode.

i2c.scan()

Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond. Only valid when in master mode.

Constants

I2C.MASTER

for initialising the bus to master mode