This logger measures the temperature every five minutes and saves it to a file on the Pico. Leave it in a greenhouse, a loft or a fridge for a few days, then copy the file to your computer and draw a graph in any spreadsheet. Along the way you'll use a digital sensor on the 1-Wire bus, the Pico's own file system, and a timing trick that keeps readings exactly five minutes apart.
What you need
- A Raspberry Pi Pico of any kind, with headers, and a USB cable that carries data
- A DS18B20 temperature sensor. The bare 3-leg version (it looks like a transistor) or the waterproof probe on a cable both work.
- One 4.7 kΩ resistor (yellow, violet, red)
- A breadboard, some jumper wires, and Thonny on your computer
Why the DS18B20?
The Pico has a temperature sensor built into its chip, but it measures the chip, which warms up as it works, and it's only accurate to a few degrees. The DS18B20 is a separate digital sensor. Its datasheet gives ±0.5 °C from −10 °C to +85 °C, and it sends the reading as a number, so long wires don't add error the way they would with an analogue sensor. It runs from 3.0 to 5.5 V, so the Pico's 3.3 V suits it.
It talks over a 1-Wire bus: one data line, shared by any number of sensors, each with its own 64-bit address. The data line is "open drain", which means devices can only pull it low. The 4.7 kΩ pull-up resistor pulls it back up to 3.3 V between bits. Without it, the Pico won't find the sensor at all.
The circuit
Hold the bare sensor with its flat, printed side facing you and the legs pointing down. From left to right the legs are GND, DQ (data) and VDD (power).
| DS18B20 | Probe wire (usually) | Connect to |
|---|---|---|
| GND (left leg) | Black | GND, Pico pin 28 |
| DQ (middle leg) | Yellow or white | GP22, Pico pin 29 |
| VDD (right leg) | Red | 3V3(OUT), Pico pin 36 |
| 4.7 kΩ resistor | Between DQ and 3V3(OUT) | |
Probe colours vary between sellers, so check the listing if yours are different. Our Pico pinout guide shows where each pin is.
Step 1: wire it up
- Unplug the Pico. Push it into the breadboard across the centre gap.
- Put the sensor's three legs in three separate rows.
- Jumper the left leg (GND) to pin 28, GND.
- Jumper the middle leg (DQ) to pin 29, GP22.
- Jumper the right leg (VDD) to pin 36, 3V3(OUT). Don't use VBUS or VSYS, which carry about 5 V.
- Put the 4.7 kΩ resistor from the middle leg's row to the right leg's row.
Step 2: check the sensor
Plug the Pico in, open Thonny, make sure MicroPython is selected at the bottom right, and run this:
from machine import Pin
import onewire, ds18x20, time
sensor = ds18x20.DS18X20(onewire.OneWire(Pin(22)))
roms = sensor.scan()
print("Found", len(roms), "sensor(s)")
sensor.convert_temp()
time.sleep_ms(750)
print(sensor.read_temp(roms[0]), "°C")
You should see Found 1 sensor(s) and a sensible room temperature. Hold the sensor between your fingers, run it again, and the number should rise. The onewire and ds18x20 modules come with MicroPython for the Pico, so there's nothing to install.
If it finds 0 sensors, the pull-up resistor or the data wire is in the wrong row. If you get exactly 85.0 °C, that's the value the sensor holds at power-up before its first conversion, which usually means the power connection is loose.
Step 3: the logger
Paste this into a new file. Save it to the Pico as main.py, so it starts by itself whenever the Pico is powered, then click Run.
from machine import Pin
import onewire, ds18x20, time, os
INTERVAL_S = 300 # seconds between readings (5 minutes)
FILE = "log.csv"
MIN_FREE = 20_000 # stop logging when flash has less than this many bytes free
led = Pin("LED", Pin.OUT)
sensor = ds18x20.DS18X20(onewire.OneWire(Pin(22))) # data line on GP22
roms = sensor.scan()
if not roms:
raise RuntimeError("No DS18B20 found. Check the wiring and the 4.7k pull-up resistor.")
rom = roms[0]
def free_bytes():
st = os.statvfs("/")
return st[0] * st[3] # block size x free blocks
def read_temp():
sensor.convert_temp()
time.sleep_ms(750) # a 12-bit conversion takes up to 750 ms
try:
return sensor.read_temp(rom)
except Exception: # CRC error, for example a loose wire
return None
if FILE not in os.listdir():
with open(FILE, "w") as f:
f.write("minutes,clock,temp_c\n")
n = 0
next_t = time.ticks_ms()
while True:
led.on()
t = read_temp()
y, mo, d, h, mi, s = time.localtime()[:6]
clock = "%04d-%02d-%02d %02d:%02d:%02d" % (y, mo, d, h, mi, s)
minutes = n * INTERVAL_S / 60
value = "" if t is None else "%.2f" % t
print(minutes, clock, value)
if free_bytes() < MIN_FREE:
print("Flash nearly full, logging stopped.")
led.off()
break
with open(FILE, "a") as f:
f.write("%.1f,%s,%s\n" % (minutes, clock, value))
led.off()
n += 1
next_t = time.ticks_add(next_t, INTERVAL_S * 1000)
while time.ticks_diff(next_t, time.ticks_ms()) > 0:
time.sleep_ms(100)
The Pico's LED blinks once each time it takes a reading. Each reading is also printed in Thonny's shell, so you can watch the first few arrive.
How it works
- Taking a reading.
convert_temp()tells the sensor to measure. At its full 12-bit resolution, steps of 0.0625 °C, that takes up to 750 ms, so the code waits that long beforeread_temp(). - Bad readings. Every reading carries a checksum. If a loose wire corrupts it,
read_temp()raises an error. The code catches it and writes an empty value, so one glitch leaves a gap in your graph rather than stopping the logger. - Exact timing. A simple
time.sleep(300)after each reading would drift, because the reading itself takes time. Instead the code works out when the next reading is due withtime.ticks_add()and waits until then.ticks_diff()handles the moment the Pico's millisecond counter wraps around, every 12 days or so. - Saving safely. The file is opened, written and closed for every reading. MicroPython stores files on the Pico's flash using LittleFS, which is designed to survive power cuts, so at worst you lose the reading that was being written.
- Space. Each line is about 35 bytes, or about 10 KB a day at one reading every five minutes. A Pico has at least several hundred kilobytes free for files, which is well over a month of readings. The code stops when less than 20 KB is left, rather than filling the flash.
Step 4: get your data
- Plug the Pico into your computer and open Thonny. Click the red Stop button to pause the logger.
- Choose View, then Files. Right-click
log.csvin the Raspberry Pi Pico pane and choose Download. - Open the file in Excel, LibreOffice Calc or Google Sheets, select the
minutesandtemp_ccolumns, and insert a line chart. - To start a fresh log, delete
log.csvfrom the Pico in the same pane. The logger creates a new one with headings next time it starts.
minutes column is meaningful. A Pico W can fetch the time from the internet. See "Take it further".Troubleshooting
- "No DS18B20 found": check the 4.7 kΩ resistor goes from the data row to the 3.3 V row, and the data wire is on pin 29. Count the pins from the end without the USB socket if unsure.
- Readings stuck at 85.0: the sensor is resetting, usually because of a poor power connection. Push the jumpers in firmly.
- Lots of empty readings: a loose connection or a very long probe cable. Firm up the wiring. For cables longer than a few metres, try a lower pull-up such as 2.2 kΩ.
- Nothing happens on a USB charger: the file must be saved on the Pico as exactly
main.py. - Thonny can't stop it: click Stop a couple of times. Thonny interrupts the program, and the log file keeps every reading saved so far.
Take it further
- More sensors. Add more DS18B20s to the same three rows.
scan()finds them all. Loop overromsand write one column per sensor. - Real time on a Pico W. Connect to Wi-Fi as in the Wi-Fi switch project, then call
ntptime.settime()to set the clock in UTC. - Faster logging. Change
INTERVAL_S. Below about 2 seconds the 750 ms conversion becomes a large part of each cycle. - Learn how the bus behind this works in our guide to I2C, SPI and UART, which compares it with the other common buses.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.