| ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ |
|---|
Generic I2C Device
Connect I2C and Qwiic devices to your LEGO MINDSTORMS or SPIKE hub. Use custom electronics at your own risk!
The pinout is shown below. Note the orientation of the connector. For EV3, the internal wire colors match those on the diagram below.
Pin |
EV3 ( |
Powered Up ( |
Powered Up ( |
|---|---|---|---|
1 (white) |
Optional battery power |
Motor Terminal 1 |
Motor Terminal 1 |
2 (black) |
N/A |
Motor Terminal 2 |
Motor Terminal 2 |
3 (red) |
Ground |
Ground |
Ground |
4 (green) |
VCC (5 V) |
VCC (3.3 V) |
VCC (3.3 V) |
5 (yellow) |
SCL (master) (3.3 V) |
SCL (master) (3.3 V) |
SDA (master) (3.3 V) |
6 (blue) |
SDA (master) (3.3 V) |
SDA (master) (3.3 V) |
SCL (master) (3.3 V) |
Do not power 3.3V devices from the EV3 5V VCC if your device does not support it.
- class I2CDevice(port, address, mode=I2CDevice.AUTOMATIC, power_pin=0, frequency=None, reg_len=1)
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.
mode (int) – Choose
I2CDevice.AUTOMATICfor a device that can be automatically detected. ChooseI2CDevice.CUSTOM_NXTfor a custom I2C device using the NXT convention orI2CDevice.CUSTOM_QWIICfor the Qwiic convention. See the pinout.power_pin (int) – Power requirements for the device. Use
0(default) for no power on the pins. On Powered Up hubs, use1or2for pin 1 or 2, respectively. This will apply battery power to the pin, equivalent to powering a motor. On NXT and EV3, use1to apply battery power to pin 1. Use at your own risk. Applying power to the pins can damage your hub or device if you are not careful. When you use this option, you will be prompted to confirm that you understand the risks.frequency (int, Hz) – I2C clock frequency. Choose
None(default) for the platform default, which is 10 kHz on EV3 and 100 kHz on Powered Up hubs. On Powered Up hubs, values from 1000 Hz to 100 kHz are supported. The frequency applies to all ports, so the most recently createdI2CDevicedetermines it.reg_len (int) – Number of bytes used to send the register address:
1(default) or2. Use2for devices with 16-bit register addresses. The register is sent most significant byte first.
- Raises:
ValueError – If
frequencyis out of range.OSError – If
frequencyis notNoneon a platform with a fixed frequency, or if it is changed while another I2C device is busy.
- await read(reg=None, length=1) bytes
- await read(reg=None, length=1, map=callable) Any
Reads bytes starting at a given register.
- Parameters:
reg (int) – Register at which to begin reading: 0x00–0xFF, or 0x0000–0xFFFF if
reg_lenis2. UseNoneto read without writing a register address first.length (int) – How many bytes to read.
map (callable) – Optional callable to convert the returned bytes. If given, it is called with the bytes as its argument and its return value is returned instead.
- Returns:
Bytes returned from the device, or the return value of
mapif a callable was provided.
- await write(reg=None, data=None)
Writes bytes, optionally starting at a given register.
- Parameters:
- Raises:
ValueError – If the register and
datatogether are more than 255 bytes.
Examples
Reading a custom I2C sensor
This example uses the NXT Temperature Sensor as if it were a custom I2C device. It sets the resolution once, and then reads the temperature in a loop.
from pybricks.iodevices import I2CDevice
from pybricks.parameters import Port
from pybricks.tools import wait
# Initialize the NXT Temperature Sensor as a custom I2C device.
sensor = I2CDevice(Port.S1, address=0x4C, mode=I2CDevice.CUSTOM_NXT)
# Write to the configuration register (0x01) to set the resolution.
sensor.write(reg=0x01, data=bytes([0x40]))
while True:
# Read two bytes from the temperature register (0x00).
high, low = sensor.read(reg=0x00, length=2)
# Combine the bytes into a signed value in 1/256 degrees Celsius.
value = (high << 8) | low
if value >= 0x8000:
value -= 0x10000
print(value / 256)
wait(500)
Making your own sensor class
This is the same example, but now wrapped in a class. The map argument
converts the raw bytes to degrees Celsius, so temperature() returns the
value you are interested in. The temperature() method can then also be used
with await when multitasking.
from pybricks.iodevices import I2CDevice
from pybricks.parameters import Port
from pybricks.tools import wait
class MyTemperatureSensor:
def __init__(self, port):
# Initialize the NXT Temperature Sensor as a custom I2C device.
self.i2c = I2CDevice(port, address=0x4C, mode=I2CDevice.CUSTOM_NXT)
# Write to the configuration register (0x01) to set the resolution.
self.i2c.write(reg=0x01, data=bytes([0x40]))
def scale_temperature(self, data):
# Combine the bytes into a signed value in 1/256 degrees Celsius.
value = (data[0] << 8) | data[1]
if value >= 0x8000:
value -= 0x10000
return value / 256
def temperature(self):
# Read two bytes from the temperature register (0x00) and
# convert them to degrees Celsius.
return self.i2c.read(reg=0x00, length=2, map=self.scale_temperature)
sensor = MyTemperatureSensor(Port.S1)
while True:
print(sensor.temperature())
wait(500)
Using a Qwiic device
This example shows text on a SparkFun SerLCD display, connected using the Qwiic convention. It also shows how to choose a custom I2C frequency.
from pybricks.iodevices import I2CDevice
from pybricks.parameters import Port
from pybricks.tools import wait
# SparkFun SerLCD commands.
COMMAND_SETTING = 0x7C
COMMAND_CLEAR = 0x2D
COMMAND_SET_RGB = 0x2B
# Initialize the display in Qwiic mode at 50 kHz.
lcd = I2CDevice(Port.A, address=0x72, mode=I2CDevice.CUSTOM_QWIIC, frequency=50000)
# Clear display and home cursor.
lcd.write(reg=None, data=bytes([COMMAND_SETTING, COMMAND_CLEAR]))
# Write some text.
lcd.write(reg=None, data=b"Hello Pybricks!")
# Cycle backlight red, green, blue, white.
for r, g, b in [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)]:
lcd.write(reg=None, data=bytes([COMMAND_SETTING, COMMAND_SET_RGB, r, g, b]))
wait(1000)
Overview of all I2C options
This example does not represent a real device. It shows all the ways you can read and write data. Some rudimentary devices do not require a register argument or even any data, as shown below.
from pybricks.iodevices import I2CDevice
from pybricks.parameters import Port
# Initialize a device using the NXT pinout convention.
device = I2CDevice(Port.A, address=0x42, mode=I2CDevice.CUSTOM_NXT)
# Read 1 byte from register 0x10.
result = device.read(reg=0x10)
# Read 4 bytes starting at register 0x10.
result = device.read(reg=0x10, length=4)
# Read 2 bytes and convert them to a number before returning.
result = device.read(reg=0x10, length=2, map=lambda data: data[0] << 8 | data[1])
# Read 1 byte from no particular register.
result = device.read(reg=None, length=1)
# Read 0 bytes from no particular register.
device.read(reg=None, length=0)
# Write 1 byte to register 0x20.
device.write(reg=0x20, data=b"\x08")
# Write 3 bytes starting at register 0x20.
device.write(reg=0x20, data=bytes([1, 2, 3]))
# Write 1 byte to no particular register.
device.write(reg=None, data=b"\x08")
# Write 0 bytes to register 0x20.
device.write(reg=0x20, data=None)
# Write 0 bytes to no particular register.
device.write(reg=None, data=None)
Some devices use 16-bit register addresses. Use reg_len=2 for these, and
then use registers as usual.
from pybricks.iodevices import I2CDevice
from pybricks.parameters import Port
# Initialize a device that uses 16-bit register addresses.
device = I2CDevice(Port.A, address=0x29, mode=I2CDevice.CUSTOM_QWIIC, reg_len=2)
# Read 2 bytes starting at register 0x010F.
result = device.read(reg=0x010F, length=2)
# Write 1 byte to register 0x0087.
device.write(reg=0x0087, data=b"\x40")
I2C Addresses
I2C addresses are 7-bit values. However, some 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.