Set up the Raspberry Pi Pico as an analog sensor hub for the Pi

Install MicroPython on the Raspberry Pi Pico, blink its LED, then turn it into an analog sensor hub: it reads a potentiometer, a light sensor and its own temperature, and sends the readings over USB to a Raspberry Pi 4...
  • Level:Advanced
  • Duration: 1 h 30 min
  • Ages 12+
  • Platform: Raspberry Pi
Set up the Raspberry Pi Pico as an analog sensor hub for the Pi – EEMENTOR STEM™ lesson

The Raspberry Pi 4 is a full computer, but it has a gap: its GPIO pins are digital only. It can tell whether a pin is on or off, but it can't measure a voltage, so it can't read a potentiometer, a light sensor or a soil sensor on its own. The Raspberry Pi Pico can. Its RP2040 chip has an analog-to-digital converter (ADC) with three input pins. In this project you set up the Pico with MicroPython, then make it the Pi's analog sensor hub: the Pico measures a potentiometer, a light sensor and its own temperature five times a second and sends every reading over the USB cable. On the Pi, a Python program reads them and draws a live chart. Two boards, each doing what it is best at.

What you'll learn

  • How to install MicroPython on the Pico and program it from Thonny
  • How the Pico's ADC turns a voltage into a number, and how to read its built-in temperature sensor
  • Why main.py runs by itself when the Pico gets power
  • How to send data as JSON lines over USB serial
  • How to read a serial port on the Pi with pyserial and draw a live chart with matplotlib

What you need

  • Raspberry Pi Pico and a micro-USB cable that carries data (not a charge-only cable)
  • Pico header pins soldered on, so it plugs into a breadboard or takes jumper wires
  • Raspberry Pi 4 Model B with Raspberry Pi OS, set up as in the starter path
  • 10 kΩ potentiometer (ESP32 IoT Starter Kit)
  • Photoresistor module (45-in-1 Sensor Kit)
  • Breadboard and jumper wires (ESP32 IoT Starter Kit)

Look after your Pico: its pins work at 3.3 V, and the ADC pins must never see more than 3.3 V. Power the sensors from the Pico's 3V3(OUT) pin, never from VBUS or VSYS (those carry 5 V from USB). Unplug the USB cable before you change the wiring.

Step 1: Install MicroPython on the Pico

  1. On the Pi, download the latest MicroPython .uf2 file for the Raspberry Pi Pico (the plain Pico, not the Pico W or Pico 2) from micropython.org/download/RPI_PICO.
  2. Hold down the white BOOTSEL button on the Pico, plug it into one of the Pi's USB ports, then let go. The Pico appears as a USB drive called RPI-RP2.
  3. Drag the .uf2 file onto that drive. The drive disappears after a few seconds: the Pico has restarted with MicroPython.

Thonny can do the same for you: click the interpreter name in the bottom-right corner of Thonny, choose Install MicroPython…, and pick the Raspberry Pi Pico variant while the Pico is in BOOTSEL mode.

Step 2: Blink the Pico's LED

In Thonny, click the interpreter name in the bottom-right corner and choose MicroPython (Raspberry Pi Pico). The Shell now shows the MicroPython prompt >>>: everything you type there runs on the Pico, not on the Pi. Paste this program into a new file and click Run:

# Blink the Pico's onboard LED
from machine import Pin
import time

led = Pin("LED", Pin.OUT)   # the green LED next to the USB socket

while True:
    led.toggle()
    time.sleep(0.5)

The small green LED next to the USB socket blinks. The name "LED" always means the board's own LED, so you don't need to remember its pin number (GP25 on the original Pico). Press Stop before the next step.

Wiring

Push the potentiometer and the photoresistor module into the breadboard. Put the Pico below the breadboard and connect it with jumper wires. The analog pins sit together on one edge, near the USB end: pins 31 to 36.

Breadboard wiring diagram: 10 kilohm potentiometer wiper to GP26 / ADC0 (pin 31), photoresistor module S to GP27 / ADC1 (pin 32), plus rail to 3V3(OUT) (pin 36) and minus rail to AGND (pin 33) on a Raspberry Pi Pico.
Breadboard view. Check each connection against the wiring table below.
From To (Pico)
Potentiometer middle pin (wiper) GP26 / ADC0 (pin 31)
Photoresistor module S GP27 / ADC1 (pin 32)
Potentiometer one outer pin, photoresistor module middle (+) The red (+) rail
Potentiometer other outer pin, photoresistor module − The blue (−) rail
The red (+) rail 3V3(OUT) (pin 36)
The blue (−) rail AGND (pin 33)

AGND is the Pico's quiet analog ground. Any GND pin works, but AGND keeps the readings a little steadier.

Step 3: The sensor hub program for the Pico

Paste this program into a new file in Thonny. Click File → Save as…, choose Raspberry Pi Pico, and save it as main.py. The Pico runs main.py by itself every time it gets power, even without Thonny. Click Run to start it now.

# Pico analog sensor hub: reads three analog inputs and prints one JSON line per reading.
# Save it on the Pico as main.py so it starts by itself when the Pico gets power.
from machine import ADC, Pin
import json
import time

pot = ADC(26)        # GP26 = ADC0, potentiometer wiper
light = ADC(27)      # GP27 = ADC1, photoresistor module S pin
sensor = ADC(4)      # ADC4 = the temperature sensor inside the RP2040
led = Pin("LED", Pin.OUT)

VOLTS_PER_STEP = 3.3 / 65535

def average(adc, samples=8):
    total = 0
    for _ in range(samples):
        total += adc.read_u16()
    return total // samples

def percent(adc):
    return round(average(adc) * 100 / 65535, 1)

def pico_temperature():
    volts = average(sensor) * VOLTS_PER_STEP
    return round(27 - (volts - 0.706) / 0.001721, 1)

while True:
    reading = {
        "ms": time.ticks_ms(),
        "pot": percent(pot),
        "light": percent(light),
        "temp": pico_temperature(),
    }
    print(json.dumps(reading))
    led.toggle()               # the LED flickers while data is flowing
    time.sleep(0.2)            # five readings per second

Five lines a second scroll through the Shell, such as {"ms": 18200, "pot": 47.3, "light": 61.8, "temp": 24.9}. Turn the potentiometer and cover the light sensor with your hand: the numbers follow. Depending on how your module is wired, the light number goes either up or down when it gets darker; both are fine.

Step 4: The live chart on the Raspberry Pi

Now let the Pi read the data instead of Thonny. Only one program can open the Pico's serial port at a time, so first click Stop in Thonny and then Run → Disconnect (or close Thonny). Unplug the Pico and plug it in again: main.py starts and the LED flickers.

Open a Terminal on the Pi and make sure the two libraries are there (they often are already):

sudo apt install python3-serial python3-matplotlib

Save this program in your home folder as hub_plot.py, and run it with python3 hub_plot.py in the Terminal (or switch Thonny back to the Local Python 3 interpreter and click Run):

# Runs on the Raspberry Pi 4: reads the Pico's JSON lines over USB and draws a live chart.
import collections
import json

import serial
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

PORT = "/dev/ttyACM0"      # the Pico's USB serial port on the Pi
POINTS = 150               # about 30 seconds of history at 5 readings per second

def parse(line):
    """Turn one line from the Pico into a dict, or None if it isn't a reading."""
    try:
        data = json.loads(line)
    except ValueError:
        return None
    if not isinstance(data, dict) or not {"pot", "light", "temp"} <= data.keys():
        return None
    return data

def main():
    pico = serial.Serial(PORT, 115200, timeout=0.1)
    history = {key: collections.deque([0.0] * POINTS, maxlen=POINTS) for key in ("pot", "light", "temp")}

    fig, (top, bottom) = plt.subplots(2, 1, sharex=True, figsize=(8, 5))
    fig.suptitle("Pico sensor hub")
    pot_line, = top.plot(history["pot"], label="Potentiometer %")
    light_line, = top.plot(history["light"], label="Light %")
    top.set_ylim(0, 100)
    top.legend(loc="upper left")
    temp_line, = bottom.plot(history["temp"], color="tab:red", label="Pico temperature °C")
    bottom.set_ylim(10, 40)
    bottom.legend(loc="upper left")
    bottom.set_xlabel("Last 150 readings")

    def update(_frame):
        while pico.in_waiting:
            reading = parse(pico.readline().decode(errors="ignore").strip())
            if reading:
                for key in history:
                    history[key].append(reading[key])
        pot_line.set_ydata(history["pot"])
        light_line.set_ydata(history["light"])
        temp_line.set_ydata(history["temp"])
        return pot_line, light_line, temp_line

    animation = FuncAnimation(fig, update, interval=200, cache_frame_data=False)
    plt.show()

if __name__ == "__main__":
    main()

A window opens with two charts that scroll along: the potentiometer and the light level in percent on top, the Pico's temperature at the bottom. Close the window to stop the program.

What you should see

Thonny Shell showing one JSON line per reading from the Pico, and the live chart on the Raspberry Pi 4 with the potentiometer, light level and Pico temperature.
The Pico sends five readings a second; the Pi draws them as a scrolling chart.

How it works

How it works: the ADC turns 0 to 3.3 volts into 0 to 65535, the RP2040 temperature formula on ADC4, and JSON lines travelling over USB to the Pi.
The Pico measures, the Pi shows.

The ADC compares the voltage on a pin with the 3.3 V reference and turns it into a number. The RP2040's converter is 12-bit, but MicroPython's read_u16() always scales the result to the range 0 to 65,535, so 0 means 0 V and 65,535 means 3.3 V. The potentiometer is a voltage divider: its wiper slides from 0 V to 3.3 V, and percent() turns that into 0 to 100. The program takes eight readings and averages them, which smooths out the small jitter every ADC has.

ADC channel 4 isn't a pin: it is a temperature sensor inside the chip. Its voltage falls by about 1.7 mV for every degree, and the RP2040 datasheet gives the formula 27 − (volts − 0.706) / 0.001721. It measures the chip itself, so it usually reads a few degrees above the room, and each chip is a little different. It is perfect for seeing changes, not for an exact room temperature.

Each reading is packed into a JSON line, the same text format web pages use. print() sends it over the USB cable, which the Pi sees as a serial port called /dev/ttyACM0. On the Pi, parse() turns each line back into a dictionary and ignores anything else, like the MicroPython welcome message. FuncAnimation calls update() every 200 ms, which reads every waiting line and redraws the charts. A deque with a maximum length keeps only the newest 150 readings, so the chart scrolls instead of growing forever.

Try this next

  • Add a third sensor on GP28 / ADC2 (pin 34), such as the soil moisture module, and give it its own line on the chart.
  • Save every reading on the Pi to a CSV file as well, so you can open it in a spreadsheet later.
  • Send commands the other way: let the Pi switch the Pico's LED by writing a line to the port.

Troubleshooting

  • No RPI-RP2 drive appears: hold BOOTSEL before you plug in the cable, and try another cable. Many micro-USB cables only charge.
  • "could not open port /dev/ttyACM0" or "Device or resource busy": Thonny is still connected to the Pico. Disconnect or close Thonny, then unplug and replug the Pico. If the Pico shows up as /dev/ttyACM1, change PORT.
  • The potentiometer always reads 0 or 100: the wiper (middle pin) must go to GP26, and the outer pins to the + and − rails.
  • The chart stays flat: check that main.py is saved on the Pico (not on the Pi) and that the LED flickers. If it doesn't, the program isn't running.
  • The temperature looks too high: that is normal; it is the chip's temperature, see How it works.

Next lesson

Previous: Show motion in 3D in the browser with an MPU-6050. Next: Build a reaction timer on a 4-digit display with the Pico, where the Pico works on its own with timer interrupts.