Try Embedded

Pico 2 in MicroPython: a second core with _thread

MicroPython on a Raspberry Pi Pico 2 starts a function on core 1 with thread. Core 1 reads a knob a few hundred times a second and smooths it; core 0 dims an…

Firmware · Intermediate

In a real product: Smart dimmer with a steady sampling core (Smart home): A dimmer keeps reading its knob or sensor at a steady rate on one core while the other drives the light and talks to the app.

The RP2350 has two Cortex-M33 cores. MicroPython runs your program on core 0; _thread.start_new_thread(f, args) starts the function f on core 1, and from then on both run at the same time. Here core 1 does one steady job, reading a potentiometer and smoothing it, while core 0 sets an LED's brightness from the smoothed level and prints a report twice a second. Holding the button on GP14 pauses the report; core 1 keeps reading all the while.

What you'll learn

  • _thread.start_new_thread(): a function of your program running on the second core
  • _thread.allocate_lock() and with lock:: one core at a time on data both of them change
  • An exponential moving average in integers: level += (reading - level) >> 3
  • Why the data the cores share is all made before core 1 starts

How it works

sampler() never returns: it reads the knob, moves level an eighth of the way towards the reading, and sleeps 2 ms. With the reading and MicroPython's own work, that is about 400 readings a second. After each one it writes the level and its count into shared, inside with lock:.

main() runs on core 0. Every 10 ms it takes both numbers under the same lock, so it never sees a level from one reading with the count of another, and sets the LED's PWM duty from the level. Twice a second, unless the button is held, it prints them. In the simulation, with the knob at 70 %:

core 1 started
core 0: level 68 %   core 1 readings: 199
core 0: level 68 %   core 1 readings: 399
core 0: level 68 %   core 1 readings: 599
core 0: level 68 %   core 1 readings: 799

MicroPython on the rp2 port has no global interpreter lock: the two cores really run Python at once. A lock is how they take turns. The dictionary shared has both its keys before core 1 starts, and core 0's own variables are local to main(): a core that adds a global name while the other looks one up could make it miss, on the chip as here.

Try this

  • Turn the knob during a run: the LED follows within a few readings, and >> 3 sets how fast. Try >> 1 and >> 5.
  • Hold the button: the report stops, but the readings counted go on rising.
  • Remove the with lock: lines around the two writes and the read, then think about when core 0 can see a level and a count that do not belong together.

main.py

# MicroPython on the Raspberry Pi Pico 2 with both cores: core 1 reads a potentiometer on GP26 a few hundred times a
# second and keeps a smoothed level of it; core 0 sets an LED's brightness on GP15 from that level and prints it twice
# a second, unless the button on GP14 is held.
from machine import ADC, PWM, Pin
import _thread
import time

knob = ADC(26)
led = PWM(Pin(15), freq=1000)
button = Pin(14, Pin.IN, Pin.PULL_UP)

# What the cores share, behind one lock. Its keys are all there before core 1 starts: the cores only change values.
lock = _thread.allocate_lock()
shared = {"level": 0, "samples": 0}

# Core 1: a reading, then 2 ms of sleep; each reading moves the level an eighth of the way towards it.
def sampler():
    level = knob.read_u16()
    samples = 0
    while True:
        level += (knob.read_u16() - level) >> 3
        samples += 1
        with lock:
            shared["level"] = level
            shared["samples"] = samples
        time.sleep_us(2000)

# Core 0: the LED and the report. Its own variables are local to main().
def main():
    shown = time.ticks_ms()
    while True:
        with lock:
            level, samples = shared["level"], shared["samples"]
        led.duty_u16(level)
        if button.value() and time.ticks_diff(time.ticks_ms(), shown) >= 500:
            shown = time.ticks_ms()
            print("core 0: level", level * 100 // 65535, "%   core 1 readings:", samples)
        time.sleep_ms(10)

_thread.start_new_thread(sampler, ())
print("core 1 started")
main()

Lessons behind it