KevsRobots Learning Platform
By Kevin McAleer, 3 Minutes
In this lesson, you’ll learn about the I2C (Inter-Integrated Circuit) bus. I2C lets the Pico talk to lots of sensors and displays using just two wires, and it’s one you’ll use constantly in robot projects.
I2C uses two wires: SDA (Serial Data) and SCL (Serial Clock). It is synchronous: the Pico drives the clock, so the two sides don’t need to agree on a baud rate.
Many devices can share the same two wires. Each device has its own address, a number like 0x3C for an OLED display or 0x68 for an MPU6050 motion sensor.
The Pico has two I2C buses, I2C0 and I2C1. I2C0 on GP0 (SDA) and GP1 (SCL) is a common choice:
from machine import Pin, I2C
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
devices = i2c.scan()
print([hex(d) for d in devices])
scan() returns the address of every device that answers. It’s the first thing to run when you connect something new: if your device doesn’t show up, check the wiring before anything else.
Most I2C sensors store their settings and readings in numbered registers:
# Read 2 bytes from register 0x0F of the device at address 0x68
data = i2c.readfrom_mem(0x68, 0x0F, 2)
print(data)
# Write the byte 0x01 to register 0x10 of the device at address 0x68
i2c.writeto_mem(0x68, 0x10, b'\x01')
In practice you’ll usually use a library for your sensor or display, which does these reads and writes for you.
Problem: i2c.scan() returns [].
Solution: Check SDA and SCL aren’t swapped, that the device has power, and that you’re using the right bus number for your pins.
Why: The Pico couldn’t get any device to answer on that bus.
Quick quiz 1 of 2
How does the Pico tell several devices on the same I2C wires apart?
Quick quiz 2 of 2
What’s the quickest way to check an I2C device is wired correctly?
scan() lists every device that answers, so you can see whether yours is there.
You can use the arrows ← → on your keyboard to navigate between lessons.
Comments