PyRasp

7–10. Devices on a bus

The first six lessons used one pin at a time. Real devices often need a bus: a small set of shared wires with rules for who speaks when. This module covers the three buses on the Pico and the one display every project wants.

You do not have to memorise every register. You do need to know which wire is which, what address or baud the device expects, and how to check that it answered.

An I2C bus: the Pico drives two shared wires, SDA on GP4 and SCL on GP5, plus 3.3 V and ground. A sensor at address 0x76 and an OLED at address 0x3C both hang on the same wires.


Lesson 7 — I²C: meet a sensor

You will be able to: scan a bus, read a register, write a register, and tell “wired wrong” from “asleep”.

The idea

I²C uses two wires:

  • SDA — data, both directions;
  • SCL — the clock that says when a bit is ready.

Every device has an address (7 bits). The Pico is the controller; the sensor only answers when spoken to. Because the wires are shared, both are pulled high by resistors; many breakout boards include them, and the Pico has none.

A device's settings live in numbered registers. You write a register to configure it and read a register to learn something.

The exact tools

from machine import I2C, Pin

bus = I2C(0, sda=Pin(4), scl=Pin(5))
print(bus.scan())                       # [104] for an MPU-6050 at 0x68
value = bus.readfrom_mem(0x68, 0x75, 1) # WHO_AM_I
bus.writeto_mem(0x68, 0x6B, b"\x00")    # clear the sleep bit
print(value[0])                         # 104
  • scan() returns a list of addresses that answered. An empty list means wiring, power, or both.
  • readfrom_mem(address, register, count) and writeto_mem(address, register, data) use 8-bit register addresses here.
  • Device addresses are 7-bit; 0x68 is the same as decimal 104.
  • Pins are yours to choose: name the SDA/SCL pair, and the devices on those pins answer.

Build it

The MPU-6050 is at 0x68 on SDA GP4 and SCL GP5. Its identity register 0x75 should read 104. Its power register 0x6B starts with the sleep bit set.

from machine import I2C, Pin

bus = I2C(0, sda=Pin(4), scl=Pin(5))
print(bus.scan())
print(bus.readfrom_mem(0x68, 0x75, 1)[0])
bus.writeto_mem(0x68, 0x6B, b"\x00")
print(bus.readfrom_mem(0x68, 0x6B, 1)[0])

Expected output:

[104]
104
0

Fun fact. WHO_AM_I is a real register name, not a joke invented for this course. Most I²C chips have one; it is the first thing a driver reads, because “is anyone there?” and “are you the chip I expected?” are different questions.

Common mistakes

What you seeWhyFix
scan() returns []SDA and SCL are swapped, or the device has no powerCheck VCC/GND, then swap SDA/SCL
OSError: [Errno 5]The address did not answerScan first; use the address from the scan
WHO_AM_I reads 0 or 255The device is asleep or the bus is not connectedWake it with 0x6B, check the wires
The answer is always 0You read before the device was readyAdd a short delay or scan first
A 16-bit register address failsThis bus uses 8-bit register pointersUse an 8-bit register, or split the address

Check yourself

  1. What are the two I²C wires called, and which one carries data?
  2. What does scan() prove?
  3. Why read WHO_AM_I before trusting a sensor?

Answers: SDA carries data, SCL is the clock · that a device answered at its address · it proves the chip is the model you think it is.

Remember

  • I²C = SDA + SCL + addresses, not pin numbers.
  • Scan first; read the identity; then configure.
  • A register is a numbered setting inside the device.

Problems: Find the sensor · Wake the sensor · Is the sensor there?


Lesson 8 — I²C: draw on an OLED

You will be able to: initialise an SSD1306, draw text and shapes, and send the framebuffer to the screen.

The idea

The OLED does not understand “HELLO”. It understands commands (display on, contrast, address window) and pixels (a 1024-byte buffer for 128×64 monochrome pixels).

In MicroPython you draw into a framebuf.FrameBuffer, then send the whole buffer:

Drawing on the OLED: frame.text and frame.rect draw into a 1024-byte buffer in memory, one bit per pixel; show() sends the buffer to the 128 by 64 pixel screen.

Each I²C write has a control byte first:

  • 0x00 — the bytes that follow are commands;
  • 0x40 — the bytes that follow are pixel data.

The exact tools

The ssd1306 module is frozen into the Pico firmware, just as it is on many classroom boards. The usual three lines are all the setup you need:

from machine import I2C, Pin
from ssd1306 import SSD1306_I2C

i2c = I2C(0, sda=Pin(4), scl=Pin(5))
screen = SSD1306_I2C(128, 64, i2c)
screen.fill(0)
screen.text("PyRasp", 34, 28, 1)
screen.rect(0, 0, 128, 64, 1)
screen.show()

The display is at 0x3C on SDA GP4, SCL GP5, powered from 3V3.

SSD1306_I2C is a framebuf.FrameBuffer, so fill, text, pixel, line, rect and blit are the drawing tools you already know. Nothing appears until show() sends the buffer over I²C.

Behind the scenes the driver sends the panel's init sequence once, then writes commands with control byte 0x00 and pixel data with 0x40. You do not need to memorise the sequence to use the screen, but the next lesson looks at the bytes if you are curious.

Build it

  1. Get a blank screen with the init sequence and frame.fill(0), then send the buffer.
  2. Draw one word: frame.text("Hi", 0, 0, 1).
  3. Draw a border and a filled rectangle. The 8×8 font puts about 16 characters on a line.
  4. Clear the buffer and redraw every time you want to change the screen. Sending a new frame is easier than erasing individual pixels.

Fun fact. “OLED” stands for organic light-emitting diode. Each pixel makes its own light, so black pixels are truly off — that is why an OLED watch can show a clock all night and use almost no power.

Common mistakes

What you seeWhyFix
The screen stays blackNo show(), or power offDraw, then call show(); check VCC/GND
Garbage or a partial imageWrong size passed to the driverUse SSD1306_I2C(128, 64, i2c)
Text is upside downA different panel orientationSSD1306_I2C uses the common 128×64 orientation
The screen flickersClearing and sending in a tight loopRedraw at a sensible rate (e.g. 5–10 Hz)
OSError at 0x3CThe panel is at another address, or not wiredScan the bus; some modules are 0x3D

Check yourself

  1. What is the control byte for pixel data?
  2. How many bytes does a 128×64 monochrome buffer need?
  3. Why must you initialise the panel before drawing?

Answers: 0x40 · 1024 · it is off and unconfigured until the commands arrive.

Remember

  • SSD1306_I2C(128, 64, i2c) gives you a framebuf-style screen.
  • Draw into the buffer, then call show() to send it.
  • Clear and redraw the whole frame to change the screen.

Problems: Write on the OLED · Count on the screen · Press counter on screen · A small menu · Bar graph · Sensor on screen


Lesson 9 — SPI: read a fast ADC

You will be able to: wire an MCP3008, exchange bytes with SPI, and turn the reply into a number.

The idea

SPI is a four-wire bus:

  • SCK — clock, driven by the Pico;
  • MOSI — data from the Pico to the device;
  • MISO — data from the device to the Pico;
  • CS — chip select, one per device, driven by you.

There are no addresses: the device whose CS is low is the one listening. The Pico sends a command and simultaneously receives a reply, which is why the main operation is called exchange.

The MCP3008 is an 8-channel, 10-bit ADC. Its command is three bytes:

ByteValueWhat it does
00x01start
10x80 | (ch << 4)single-ended reading, and which channel
20x00clocks out the result
reply[?, high, low]result = ((reply[1] & 0x03) << 8) | reply[2]

The exact tools

from machine import Pin, SPI
import utime

cs = Pin(17, Pin.OUT, value=1)
spi = SPI(0, baudrate=1_000_000, sck=Pin(18), mosi=Pin(19), miso=Pin(16), cs=cs)

def read(channel):
    cs.value(0)
    reply = bytearray(3)
    spi.write_readinto(bytes([1, 0x80 | (channel << 4), 0]), reply)
    cs.value(1)
    return ((reply[1] & 0x03) << 8) | reply[2]

while True:
    counts = read(0)
    print(counts, round(counts * 3.3 / 1023, 2))
    utime.sleep(0.5)

Wiring: MCP3008 VDD and VREF to 3V3, AGND and DGND to GND, CLK GP18, DIN GP19, DOUT GP16, CS GP17. The analogue input is CH0 (or CH1…CH7).

Fun fact. write_readinto sounds like a typo, but it is exact: one buffer goes out while the other comes in, one bit at a time. SPI is full duplex — it talks and listens on the same clock.

Build it

  1. Read channel 0 and print the raw count.
  2. Put a divider on CH0 and print volts as well.
  3. Read two channels in one loop: a divider on CH0 and a potentiometer on CH1.
  4. Move the CS pin to another GPIO. It still works — CS is just a pin you control.

Common mistakes

What you seeWhyFix
Always 0 or 1023MISO and MOSI swapped, or no powerCheck DIN→MOSI, DOUT→MISO, VDD/VREF
The count jumps aroundThe analogue input is floatingConnect a divider or a known voltage
Two channels read the sameThe channel bits are wrongPut the channel in the high nibble of byte 1
Nothing at allCS never goes lowcs.value(0) before, cs.value(1) after
A warning about the busA device is missing or miswiredCheck the four SPI wires and power

Check yourself

  1. Which SPI wire does the Pico use to send data?
  2. Why does CS exist if SPI has no addresses?
  3. What is the range of the MCP3008's result?

Answers: MOSI · CS chooses which device is listening · 0–1023 (10 bits).

Remember

  • SPI = SCK, MOSI, MISO, CS; the Pico drives the clock.
  • Lower CS, exchange, raise CS.
  • MCP3008: three bytes out, three bytes in, 10-bit result.

Problems: Read a channel · Two channels


Lesson 10 — UART: listen to a GPS

You will be able to: connect a serial device, read a line, and recognise an NMEA sentence.

The idea

UART is the oldest bus here: two wires, TX (transmit) and RX (receive), and a shared speed called baud. There is no clock wire; both ends agree on the timing in advance.

The GPS sends text sentences once a second, even if nobody is listening. You read a line and parse it:

One GPS sentence, $GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A, with its fields labelled: sentence type, time 12:35:19 UTC, status A meaning valid, latitude 48 degrees 7.038 minutes north, longitude 11 degrees 31 minutes east, speed 22.4 knots.

The exact tools

from machine import UART, Pin
import utime

uart = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))

while True:
    if uart.any():
        line = uart.readline()
        print(line)
    utime.sleep_ms(50)

Wiring: Pico GP0 (TX) → GPS RX, GPS TX → Pico GP1 (RX), VCC 3V3, GND. The GPS NEO-6M defaults to 9600 baud.

readline() waits for a newline in simulated time. any() tells you whether bytes are waiting, so the loop does not block forever.

Fun fact. NMEA sentences start with $ and end with * and a two-digit checksum. The format predates GPS: it was used for marine electronics in the 1980s. Your phone still speaks it.

Build it

  1. Print one line. You should see $GPRMC or $GPGGA.
  2. Split the line on commas and print the first three fields.
  3. Print only the sentences that start with $GPRMC.
  4. Convert a latitude from 4807.038 (degrees and minutes) to decimal degrees: 48 + 07.038/60.

Common mistakes

What you seeWhyFix
Nothing, or garbageTX and RX are not crossedPico TX → device RX; device TX → Pico RX
Garbage with some senseWrong baudBoth ends at 9600
b'$GPRMC...' and string methods failYou have bytes, not strDecode: line.decode()
The program freezesreadline() with no newline and no timeoutUse any() first, or readinto with a timeout
A checksum errorA sentence was cut in halfRead a whole line, then parse

Check yourself

  1. Which Pico pin receives data in this lesson?
  2. What does 9600 baud mean?
  3. Why check uart.any() before reading?

Answers: GP1 · 9600 bits per second, agreed by both ends · so a read does not block forever.

Remember

  • UART = TX, RX, and a shared baud rate.
  • Cross TX to RX; do not cross TX to TX.
  • NMEA is comma-separated text with a checksum.

Problems: Listen to the GPS · Read the GPS type


The device checklist

Before you debug code, check these five things. They cause more failures than logic does.

  1. Power: VCC to 3V3, GND to GND, and the module's LED (if it has one) is on.
  2. Wires: SDA/SCL, MOSI/MISO, TX/RX are easy to swap. Say each one out loud.
  3. Address or baud: I²C needs the address; UART needs the same baud; SPI needs the right CS.
  4. Pull-ups: the Pico has no I²C pull-ups; breakout boards usually do.
  5. One change at a time: if you move two wires and it works, you do not know which one fixed it.

A debugging habit. Write a five-line program that only scans or reads an identity register. When it works, add your real program. If the real program then fails, the bus is not the problem.

Next