Pico 2 in MicroPython: a thermometer with an alarm light
MicroPython on a Raspberry Pi Pico 2 reads an NTC thermistor on its ADC, works out the temperature with the Steinhart-Hart formula, and lights a warning LED…
Sensors · Beginner
In a real product: Fridge temperature alarm (Consumer electronics): A fridge shows a warning light when its inside warms past a safe temperature.
An NTC thermistor's resistance falls as it warms. Wired as a voltage divider to GP26, its voltage tells the temperature. This MicroPython program on a Pico 2 reads it twice a second, turns the reading into degrees Celsius, and lights a red LED on GP15 above 8 °C, the warning point of a fridge. The board's own LED blinks to show the program is alive.
What you'll learn
- Reading an analog voltage in MicroPython with
ADC(26).read_u16()(0 to 65535 for 0 to 3.3 V) - The beta form of the Steinhart-Hart equation, which turns a thermistor's resistance into a temperature
- Hysteresis: switching the alarm off a little below the point it switched on, so it does not flicker
How it works
The module's NTC (10 kΩ at 25 °C, beta 3950) sits in a divider. From the reading raw, its resistance is R = 10000 * raw / (65535 - raw), and the temperature in kelvin is 1 / (ln(R / 10000) / 3950 + 1 / 298.15). The Pico 2 does that maths on the Cortex-M33's floating-point unit (MicroPython's floats are single precision there).
The alarm turns on above 8.0 °C and off again only below 7.5 °C. Without that half degree of hysteresis, a temperature sitting right at 8 °C would switch the light on and off with every bit of noise.
Try this
- Move the sensor's temperature slider in the simulation above 8 °C and back: watch the light and the printout.
- Change the limits to a freezer's: alarm above -15 °C.
- Average four readings before converting, and see the printed temperature steady.
main.py
# MicroPython on the Raspberry Pi Pico 2: an NTC thermistor module on GP26 (ADC0), a warning LED on GP15 above 8 C,
# the board's LED (GP25) blinking while the program runs.
from machine import ADC, Pin
import math
import time
sensor = ADC(26)
alarm = Pin(15, Pin.OUT)
led = Pin("LED", Pin.OUT)
ON, OFF = 8.0, 7.5 # degrees C: on above ON, off below OFF
warm = False
def celsius(raw):
r = 10000 * raw / (65535 - raw)
return 1 / (math.log(r / 10000) / 3950 + 1 / 298.15) - 273.15
while True:
t = celsius(sensor.read_u16())
if t > ON:
warm = True
elif t < OFF:
warm = False
alarm.value(warm)
led.toggle()
print("%.1f C %s" % (t, "WARM" if warm else "ok"))
time.sleep(0.5)