Try Embedded

Pico 2 in MicroPython: five minutes of temperature in RAM

MicroPython on a Raspberry Pi Pico 2 reads a thermistor a thousand times a second on a timer and keeps the last five minutes, 300 000 readings, in one…

Sensors · Beginner

In a real product: Cold-chain temperature logger (Medical): A vaccine fridge's logger keeps the recent readings, so a door left open shows up as a dip in the history.

MicroPython keeps its objects on a heap in the chip's RAM. On a Pico (RP2040) that heap is about 230 KB; on a Pico 2 (RP2350, 520 KB of SRAM) it is about 480 KB. This program asks for a single 300 000-byte bytearray, five minutes of readings at 1000 a second, a byte each, and fills it from a timer. A Pico runs out of memory at that line; a Pico 2 still has 180 KB free after it. A button on GP14 prints a summary of the history.

What you'll learn

  • gc.mem_free(): how much of MicroPython's heap is left, before and after a big allocation
  • A ring buffer in a bytearray, indexed by a running count (history[taken % N])
  • machine.Timer(freq=1000, callback=...): a function run at a steady rate, whatever the main loop is doing
  • Keeping 8 bits of a 16-bit ADC reading (read_u16() >> 8) to halve the memory a reading needs

How it works

gc.collect() first tidies the heap, so mem_free() is a true figure. bytearray(300_000) then takes one block of 300 000 bytes. (An array("H") of 16-bit readings would be 600 000 bytes for the same five minutes: more than there is.)

The timer calls sample() 1000 times a second. It stores the reading's top 8 bits, 0 to 255 for 0 to 3.3 V, and adds one to taken. The main loop prints the count each second and calls report() on a press of the button, which walks the readings the buffer holds. In the simulation, with the sensor at 24 °C:

free before: 480976 bytes
history: 300000 bytes; free after: 180960 bytes
readings taken: 1000  newest: 130
readings taken: 2000  newest: 130
--- the last 2.92 s: min 130 max 130 mean 130.0

On a Pico the second line is MemoryError: memory allocation failed, allocating 300000 bytes.

Try this

  • Move the sensor's temperature slider during a run, then press the button: the minimum and maximum show the change.
  • Turn a reading back into degrees Celsius in report(), with the Steinhart-Hart formula of the thermometer project.
  • Make the history ten minutes long (N = 600 * RATE) and see where MicroPython says no.

main.py

# MicroPython on the Raspberry Pi Pico 2: the last 5 minutes of an NTC thermistor on GP26 (ADC0) at 1000 readings a
# second, 300 000 of them in a 300 KB bytearray; a button on GP14 prints a summary of them.
from machine import ADC, Pin, Timer
import gc
import time

RATE = 1000                         # readings a second
N = 300 * RATE                      # 5 minutes of them, a byte each

gc.collect()
print("free before:", gc.mem_free(), "bytes")
# 300 000 bytes: more than a Pico's MicroPython has free in all.
history = bytearray(N)
print("history:", len(history), "bytes; free after:", gc.mem_free(), "bytes")

sensor = ADC(26)
button = Pin(14, Pin.IN, Pin.PULL_UP)
taken = 0                           # readings since the start: the newest is history[(taken - 1) % N]

# 1000 times a second: the reading's top 8 bits (0 to 255 for 0 to 3.3 V).
def sample(_):
    global taken
    history[taken % N] = sensor.read_u16() >> 8
    taken += 1

timer = Timer(freq=RATE, mode=Timer.PERIODIC, callback=sample)

def report():
    end, count = taken, min(taken, N)
    lo, hi, total = 255, 0, 0
    for i in range(end - count, end):
        v = history[i % N]
        lo, hi, total = min(lo, v), max(hi, v), total + v
    print("--- the last", count / RATE, "s: min", lo, "max", hi, "mean", total / count)

was = 1
shown = time.ticks_ms()
while True:
    pressed = button.value() == 0
    if pressed and was:
        report()
    was = not pressed
    if time.ticks_diff(time.ticks_ms(), shown) >= 1000:
        shown = time.ticks_ms()
        print("readings taken:", taken, " newest:", history[(taken - 1) % N])
    time.sleep_ms(20)

Lessons behind it