How cold does the garden shed get at night? How warm is the fridge door after it has been opened? To find out you need a data logger: a small device that measures on its own for hours or days and keeps every reading, even when its battery runs out or someone pulls the plug. In this project the Raspberry Pi Pico becomes exactly that. Powered from a USB power bank, it reads a DS18B20 temperature sensor once a minute and writes each reading to a file on its own flash memory. A button lets you mark moments, like "door opened". Later you plug the Pico into a Raspberry Pi 4, and a Python program sets the Pico's clock, downloads the whole log and draws a chart.
What you'll learn
- How to read a DS18B20 on the 1-Wire bus with MicroPython's built-in
onewireandds18x20modules - How to save data so it survives a power cut, and how to look after the flash memory
- How to keep counting after a restart by reading the end of the log
- How to design a tiny command protocol between two boards:
TIME,DUMPandCLEAR - Why the Pico's clock forgets the time, and how the Pi sets it again
What you need
- Raspberry Pi Pico with MicroPython and header pins, and a micro-USB data cable (see lesson 8)
- Raspberry Pi 4 Model B with Raspberry Pi OS
- DS18B20 temperature sensor module (45-in-1 Sensor Kit)
- 1 push button, a breadboard and jumper wires (any kit, for example the ESP32 IoT Starter Kit)
- A USB power bank, to run the logger away from the computer
Look after your Pico: power the DS18B20 module from 3V3(OUT), not from VBUS or VSYS. The module's pull-up resistor connects the data line to its + pin, so a 5 V supply would put 5 V on a Pico pin and could damage it. Most modules have the 4.7 kΩ pull-up resistor on board. If you use a bare three-leg sensor instead, add a 4.7 kΩ resistor between its data leg and 3V3. Unplug the USB cable before you change the wiring.
Wiring

| From | To (Pico) |
|---|---|
| DS18B20 module S (signal) | GP22 (pin 29) |
| DS18B20 module middle (+) | The red (+) rail → 3V3(OUT) (pin 36) |
| DS18B20 module − | The blue (−) rail → GND (pin 23) |
| Mark button, one leg | GP21 (pin 27) |
| Mark button, the diagonally opposite leg | The blue (−) rail |
The logger program for the Pico
Connect the Pico to Thonny, paste the program into a new file and save it on the Pico as main.py. Click Run: the Shell prints Logger ready: boot 1 sensors 1 and a LOG line straight away, then one a minute. The Pico's LED gives a short blink every two seconds to show it is alive.
# Pico temperature logger that keeps its data through power cuts.
# Logs the DS18B20 temperature once a minute to log.csv on the Pico's own flash.
# Commands from the Pi over USB: "TIME y m d weekday h m s", "DUMP", "CLEAR".
from machine import Pin, RTC, Timer
import onewire, ds18x20
import os
import select
import sys
import time
LOG = "log.csv"
HEADER = "n,boot,minute,time,temp_c,mark\n"
INTERVAL_MS = 60_000 # one reading a minute: gentle on the flash
MIN_FREE = 50_000 # stop logging when less than 50 KB of flash is left
sensor = ds18x20.DS18X20(onewire.OneWire(Pin(22))) # DS18B20 data on GP22
roms = sensor.scan()
mark_button = Pin(21, Pin.IN, Pin.PULL_UP) # press to mark an event
led = Pin("LED", Pin.OUT)
rtc = RTC()
clock_set = False
# Heartbeat: a short blink every 2 seconds shows the logger is alive
beat = [0]
def heartbeat(t):
beat[0] = (beat[0] + 1) % 20
led.value(1 if beat[0] == 0 else 0)
blinker = Timer(mode=Timer.PERIODIC, period=100, callback=heartbeat)
marked = [False]
last_press = [0]
def on_press(pin):
now = time.ticks_ms()
if time.ticks_diff(now, last_press[0]) > 300:
last_press[0] = now
marked[0] = True
mark_button.irq(trigger=Pin.IRQ_FALLING, handler=on_press)
def last_row():
"""Read the last line of the log, so numbering carries on after a power cut."""
try:
with open(LOG) as f:
last = None
for line in f:
last = line
parts = last.strip().split(",")
return int(parts[0]), int(parts[1])
except (OSError, ValueError, IndexError, AttributeError):
return 0, 0
def free_bytes():
s = os.statvfs("/")
return s[0] * s[3]
def read_temperature():
if not roms:
return None
sensor.convert_temp()
time.sleep_ms(750) # the DS18B20 needs up to 750 ms per reading
return sensor.read_temp(roms[0])
def stamp():
if not clock_set:
return "" # the clock isn't set yet: only the minute counter
y, mo, d, h, mi, s = time.localtime()[:6]
return "{:04d}-{:02d}-{:02d} {:02d}:{:02d}".format(y, mo, d, h, mi)
def write_row(mark):
global n
temp = read_temperature()
if temp is None:
print("No DS18B20 found: check the wiring")
return
if free_bytes() < MIN_FREE:
print("Flash nearly full: DUMP the log, then CLEAR it")
return
n += 1
minute = time.ticks_diff(time.ticks_ms(), started) // 60_000
row = "{},{},{},{},{:.2f},{}\n".format(n, boot, minute, stamp(), temp, 1 if mark else 0)
new = LOG not in os.listdir()
with open(LOG, "a") as f: # append, and close at once so the data is saved
if new:
f.write(HEADER)
f.write(row)
print("LOG", row.strip())
def handle(command):
global clock_set, n
parts = command.split()
if not parts:
return
if parts[0] == "TIME" and len(parts) == 8:
y, mo, d, wd, h, mi, s = (int(p) for p in parts[1:])
rtc.datetime((y, mo, d, wd, h, mi, s, 0))
clock_set = True
print("OK TIME", stamp())
elif parts[0] == "DUMP":
print("BEGIN")
try:
with open(LOG) as f:
for line in f:
print(line.strip())
except OSError:
pass
print("END")
elif parts[0] == "CLEAR":
try:
os.remove(LOG)
except OSError:
pass
n = 0
print("OK CLEAR")
n, boot = last_row()
boot += 1 # every power-up starts a new "boot"
started = time.ticks_ms()
next_log = started
poll = select.poll()
poll.register(sys.stdin, select.POLLIN)
print("Logger ready: boot", boot, "sensors", len(roms))
while True:
if poll.poll(0): # a command from the Pi is waiting
handle(sys.stdin.readline().strip())
if marked[0]:
marked[0] = False
write_row(True)
if time.ticks_diff(time.ticks_ms(), next_log) >= 0:
next_log = time.ticks_add(next_log, INTERVAL_MS)
write_row(False)
time.sleep_ms(50)
Now unplug the Pico, connect it to a USB power bank and leave it somewhere interesting: on a windowsill, in the fridge door pocket, or in a room overnight. main.py starts on its own. Press the button whenever something happens that you want to see on the chart later.
Read the log on the Raspberry Pi
Bring the Pico back and plug it into the Raspberry Pi 4. Make sure Thonny isn't connected to the Pico, because only one program can use its serial port. In a Terminal, install the two libraries if they aren't there yet:
sudo apt install python3-serial python3-matplotlib
Save this program in your home folder as fetch_log.py and run it with python3 fetch_log.py:
# Runs on the Raspberry Pi 4: sets the Pico's clock, downloads its log and draws a chart.
# Usage: python3 fetch_log.py (add --clear to empty the Pico's log afterwards)
import csv
import sys
import time
from datetime import datetime
import serial
import matplotlib
matplotlib.use("Agg") # draw straight to a PNG file
import matplotlib.pyplot as plt
PORT = "/dev/ttyACM0"
def time_command(now):
"""The TIME line for the Pico: year month day weekday hour minute second."""
return "TIME {} {} {} {} {} {} {}\n".format(now.year, now.month, now.day, now.weekday(), now.hour, now.minute, now.second)
def read_dump(lines):
"""Pick the CSV rows between BEGIN and END out of everything the Pico prints."""
rows, inside = [], False
for line in lines:
if line == "BEGIN":
inside, rows = True, []
elif line == "END" and inside:
return rows
elif inside and line:
rows.append(line)
return None # no complete dump
def talk(pico, commands, timeout=10):
for c in commands:
pico.write(c.encode())
lines, end = [], time.time() + timeout
while time.time() < end:
line = pico.readline().decode(errors="ignore").strip()
if line:
lines.append(line)
if line == "END":
break
return lines
def chart(rows, png):
data = list(csv.DictReader(rows))
n = [int(r["n"]) for r in data]
temp = [float(r["temp_c"]) for r in data]
fig, ax = plt.subplots(figsize=(10, 4.5))
ax.plot(n, temp, color="tab:red", label="Temperature °C")
marks = [(int(r["n"]), float(r["temp_c"])) for r in data if r["mark"] == "1"]
if marks:
ax.scatter(*zip(*marks), color="tab:blue", zorder=3, label="Button marks")
for prev, row in zip(data, data[1:]):
if row["boot"] != prev["boot"]: # the Pico lost power and started again
ax.axvline(int(row["n"]), color="grey", linestyle="--")
ax.set_xlabel("Reading number (one a minute)")
ax.set_ylabel("°C")
ax.set_title("Pico temperature log: {} readings".format(len(data)))
ax.legend(loc="upper left")
fig.tight_layout()
fig.savefig(png)
return len(data)
def main():
pico = serial.Serial(PORT, 115200, timeout=1)
time.sleep(0.5)
lines = talk(pico, [time_command(datetime.now()), "DUMP\n"])
rows = read_dump(lines)
if rows is None:
sys.exit("No log received. Is main.py running on the Pico, and Thonny disconnected?")
stamp = datetime.now().strftime("%Y%m%d-%H%M")
with open("pico_log_{}.csv".format(stamp), "w") as f:
f.write("\n".join(rows) + "\n")
count = chart(rows, "pico_log_{}.png".format(stamp))
print("Saved {} readings to pico_log_{}.csv and the chart to pico_log_{}.png".format(count, stamp, stamp))
if "--clear" in sys.argv:
pico.write(b"CLEAR\n")
print("Log on the Pico cleared")
if __name__ == "__main__":
main()
The program saves two files next to it, such as pico_log_20261117-1405.csv (open it in LibreOffice Calc) and pico_log_20261117-1405.png with the chart. Run it with --clear to empty the Pico's log after the download, ready for the next experiment.
What you should see

How it works

Reading the sensor. The DS18B20 talks on a 1-Wire bus: one data wire carries commands and answers, and every sensor has its own 64-bit address. scan() finds the addresses, convert_temp() starts a measurement, and after 750 ms (the time a 12-bit measurement can take) read_temp() returns the temperature in °C with steps of 0.0625 °C.
Surviving power cuts. Each reading is added to log.csv with open(LOG, "a"), and the file is closed straight away. Closing it makes MicroPython's file system write everything to flash, so a power cut can only ever lose the reading that was being written at that moment. When the Pico starts again, last_row() reads the last line of the file, so the reading number carries on and the boot column goes up by one. On the chart each new boot becomes a dashed line, so you can see when the power went off.
Looking after the flash. Flash memory wears out a little every time a block is erased, after about 100,000 erases. MicroPython's file system spreads the writes over the whole flash, and one short line a minute is very gentle. Writing many times a second for months is what wears flash out. Each line is about 35 bytes, so the roughly 1.4 MB that MicroPython leaves for files holds about three to four weeks of readings. The program checks the free space with os.statvfs() and stops before the flash is full.
The clock. The Pico has a real-time clock, but no battery to keep it running, so it forgets the time at every power cut. Until it is told the time, the logger writes the minutes since it started. When the Pi connects, it first sends TIME with today's date and time, and from then on every row gets a real time stamp.
The command protocol. The Pico checks the USB serial line with select.poll() 20 times a second without waiting, so logging never stops. DUMP prints BEGIN, the whole file and END; the Pi keeps only the lines in between and ignores any LOG or OK lines around them. Clear start and end markers like these are how many real devices send files over a serial line.
Try this next
- Add a second DS18B20 on the same wire:
scan()finds both, so you can log inside and outside at once. - Log every 10 seconds while the button is held down, for quick experiments such as an ice cube melting.
- Use the analog sensor hub idea to log the light level too.
Troubleshooting
- "No DS18B20 found": check S on GP22, + on 3V3 and − on GND. A bare sensor needs the 4.7 kΩ pull-up resistor.
- The temperature reads 85 °C: that is the DS18B20's power-on value. It means the reading was taken too early or the supply is weak; check the + wire.
-
"No log received" on the Pi: close Thonny, unplug and replug the Pico, and check that
main.pyis saved on the Pico. If the port is/dev/ttyACM1, changePORT. - The logger stops when the power bank is on: some power banks switch off when the current is very small. Use one with a low-current mode, or plug it into a USB phone charger instead.
-
The time column is empty: that is normal until the Pi has sent
TIME, see How it works.
What's next
Previous: Build a reaction timer on a 4-digit display with the Pico. You have finished the Raspberry Pi advanced projects path. Combine the projects: let the Pi run the climate dashboard from lesson 1 with the Pico's readings, or send an alert from the keypad alarm when the logged temperature gets too high.