Project

Raspberry Pi Pico 2 W data logger with a local dashboard

A MicroPython v1.29.0 logger on the Raspberry Pi Pico 2 W that reads an SHT45, keeps a rotating CSV on flash, serves JSON over Wi-Fi, and a standard-library Python dashboard that charts it.

BeginnerRaspberry PiTier 1: Builds in CIUpdated 28 November 2026
BoardRaspberry Pi Pico 2 W
Timeabout 3 hours
Stackmicropython, python
Extra partsRaspberry Pi Pico 2 W, SHT45 breakout (Sensirion SHT45-AD1B) for 3.3 V, Micro-USB cable and 5 V USB supply

This project turns a Raspberry Pi Pico 2 W into a stand-alone temperature and humidity logger. The Pico reads a Sensirion SHT45 once a minute, appends each reading to a CSV (comma-separated values) file on its own flash and answers two HTTP requests on your Wi-Fi network. A small Python program on your computer polls it and draws a dashboard in the browser. It is for makers who want a logger without a cloud account or a broker, and for product teams who want to see how much of a MicroPython device can be tested before it touches hardware.

What you will build

  • fglog.py: the board-independent part. It decodes and checks the SHT45 reply, keeps the most recent 288 readings in RAM (a day at one per minute), writes every reading to log.csv and rotates the file at about 256 kB so it never fills the flash.
  • main.py: the board part. It joins Wi-Fi, sets the clock over NTP (Network Time Protocol), samples the sensor and serves GET /data.json and GET /log.csv on port 80 with MicroPython’s asyncio.
  • dashboard.py: a host program using only the Python standard library. It polls /data.json, removes duplicates, keeps its own CSV history and serves a page with two inline SVG (Scalable Vector Graphics) charts at http://127.0.0.1:8050/.

The JSON (JavaScript Object Notation) document the Pico serves has this shape, with one row per reading (Unix time, °C, %RH):

{"fields": ["ts", "t_c", "rh"], "rows": [[1764000000, 21.0, 48.0], [1764000060, 21.1, 47.8]]}

What you need

Part Why Reference
Raspberry Pi Pico 2 W RP2350 with 4 MB flash, 520 kB SRAM and an Infineon CYW43439 for 2.4 GHz Wi-Fi 4 and Bluetooth 5.2 Pico 2 W datasheet
SHT45 breakout for 3.3 V ±1.0 %RH and ±0.1 °C accuracy, I²C (Inter-Integrated Circuit) address 0x44 SHT4x datasheet v7.3
MicroPython v1.29.0 for the Pico 2 W The firmware the code was checked against: RPI_PICO2_W-20260824-v1.29.0.uf2 micropython.org
mpremote on your computer Copies files to the board mpremote docs

The RP2350 on the Pico 2 W has two Arm Cortex-M33 or two Hazard3 RISC-V cores at up to 150 MHz. MicroPython publishes builds for both, and this project uses the standard Arm build. The Wi-Fi interface is single-band 2.4 GHz 802.11n, so the Pico must join a 2.4 GHz network.

Wire the SHT45 to the Pico’s 3.3 V output, ground, GP4 (SDA) and GP5 (SCL). Those are MicroPython’s default pins for I2C(0) on Pico boards, according to the v1.29.0 quick reference. The datasheet says the 3.3 V output of the on-board regulator can power external circuits, and the SHT45 needs very little.

Design

SHT45Pico 2 WMicroPython v1.29.0main.py: Wi-Fi, NTP, HTTPfglog.py: CRC, logflash: log.csv, log.csv.1Wi-Fi APdashboard.pypolls every 30 spico-history.csvBrowser :8050GP4/5GET /data.json
Where each file runs. The Pico 2 W samples the SHT45, appends to log.csv on its flash and serves /data.json over Wi-Fi. The dashboard on a computer polls it every 30 s, keeps its own history and serves the chart page to a browser on the same computer.

Three choices keep the logger dependable.

  1. Logic apart from hardware. Everything that can be wrong without a board (CRC, conversion, log rotation, HTTP parsing) lives in fglog.py, which imports neither machine nor network. That is what lets CI run it on the MicroPython Unix port.
  2. The flash is the log of record. The RAM buffer is for the dashboard. The CSV on flash survives a reset, and /log.csv lets you download it. Rotation keeps one old file (log.csv.1), so the logger uses at most about twice the size limit.
  3. The dashboard pulls. The Pico never needs to know where the dashboard runs, and the dashboard copes with the Pico rebooting: rows are keyed by timestamp, so repeats are dropped.

The HTTP handler is deliberately small. It reads the request line, skips the headers, answers with HTTP/1.0 and closes the connection. There is no keep-alive, no chunked encoding and no query string, so there is very little to go wrong on a small device. The price is one TCP connection per poll, which at one poll every 30 s costs nothing worth measuring.

The sample loop catches two kinds of failure. OSError covers errors from the I²C bus, which usually mean a loose wire or a missing pull-up. ValueError comes from sht4x_decode() when a CRC does not match. Both are printed and the loop carries on, so one bad reading never stops the logger.

Time comes from NTP once at start-up. MicroPython’s documentation says the rp2 port counts time.time() from 1 January 1970 UTC, so the timestamps are Unix time once the clock is set. If NTP fails the logger keeps going with the unset clock and says so on the console.

Firmware

Flash MicroPython v1.29.0: hold BOOTSEL while you plug the Pico into USB, then copy RPI_PICO2_W-20260824-v1.29.0.uf2 to the drive that appears. The board resets when the copy finishes. The v1.29.0 build for this board includes the bundle-networking packages, which provide ntptime.

fglog.py, the part CI tests:

# target: rp2 (Pico 2 W) sdk: micropython v1.29.0 tier: 2
"""Board-independent logic for the Pico 2 W data logger: SHT4x decoding, the log, the HTTP handler.

No machine or network imports, so the MicroPython Unix port can test it (test_fglog_unix.py).
SHT4x figures: Sensirion SHT4x datasheet v7.3 (June 2026), sections 4.4 to 4.6.
"""
import json
import os

SHT4X_ADDR = 0x44
SHT4X_MEASURE_HI = 0xFD


def crc8(data):
    crc = 0xFF
    for b in data:
        crc ^= b
        for _ in range(8):
            crc = ((crc << 1) ^ 0x31) & 0xFF if crc & 0x80 else (crc << 1) & 0xFF
    return crc


def sht4x_decode(raw):
    """6 bytes from the sensor -> (t_degc, rh_pct). Raises ValueError on a CRC mismatch."""
    if crc8(raw[0:2]) != raw[2] or crc8(raw[3:5]) != raw[5]:
        raise ValueError("SHT4x CRC")
    t_ticks = raw[0] << 8 | raw[1]
    rh_ticks = raw[3] << 8 | raw[4]
    t = -45 + 175 * t_ticks / 65535
    rh = min(100.0, max(0.0, -6 + 125 * rh_ticks / 65535))
    return t, rh


class Log:
    """Keeps the last `keep` readings in RAM and appends every reading to a CSV file on flash.

    When the file passes max_bytes it is renamed to <path>.1 (one old file kept), so the
    logger never fills the 4 MB flash.
    """

    def __init__(self, path="log.csv", keep=288, max_bytes=256_000):
        self.path, self.keep, self.max_bytes = path, keep, max_bytes
        self.recent = []

    def add(self, ts, t, rh):
        row = (int(ts), round(t, 2), round(rh, 1))
        self.recent.append(row)
        if len(self.recent) > self.keep:
            self.recent.pop(0)
        try:
            size = os.stat(self.path)[6]
        except OSError:
            size = -1
        if size > self.max_bytes:
            try:
                os.remove(self.path + ".1")
            except OSError:
                pass
            os.rename(self.path, self.path + ".1")
            size = -1
        with open(self.path, "a") as f:
            if size < 0:
                f.write("ts,t_c,rh\n")
            f.write("%d,%.2f,%.1f\n" % row)
        return row

    def as_json(self):
        return json.dumps({"fields": ["ts", "t_c", "rh"], "rows": self.recent})


async def handle_http(reader, writer, log):
    """Minimal HTTP/1.0: GET /data.json (recent rows) and GET /log.csv (the file on flash)."""
    try:
        line = await reader.readline()
        while True:  # skip headers
            h = await reader.readline()
            if not h or h == b"\r\n":
                break
        parts = line.decode().split()
        path = parts[1] if len(parts) > 1 else "/"
        if path == "/data.json":
            body, ctype, code = log.as_json().encode(), "application/json", "200 OK"
        elif path == "/log.csv":
            try:
                with open(log.path, "rb") as f:
                    body = f.read()
                ctype, code = "text/csv", "200 OK"
            except OSError:
                body, ctype, code = b"no log yet\n", "text/plain", "404 Not Found"
        else:
            body, ctype, code = b"try /data.json or /log.csv\n", "text/plain", "404 Not Found"
        writer.write(("HTTP/1.0 %s\r\nContent-Type: %s\r\nContent-Length: %d\r\nConnection: close\r\n\r\n"
                      % (code, ctype, len(body))).encode())
        writer.write(body)
        await writer.drain()
    finally:
        writer.close()
        await writer.wait_closed()

main.py, the board glue. The user LED sits on the CYW43439 wireless chip (its WL_GPIO0), which the v1.29.0 board definition maps to the pin name "LED":

# target: rp2 (Pico 2 W) sdk: micropython v1.29.0 tier: 1
"""Pico 2 W data logger: read an SHT45 every PERIOD_S, log to flash, serve /data.json on port 80.

Copy fglog.py, main.py and secrets.py (from secrets.py.example) to the board, for example with
    mpremote cp fglog.py main.py secrets.py :
"""
import asyncio
import time

import network
import ntptime
from machine import I2C, Pin

import fglog
import secrets

PERIOD_S = 60
led = Pin("LED", Pin.OUT)          # the user LED sits on the CYW43439 (WL_GPIO0)
i2c = I2C(0, scl=Pin(5), sda=Pin(4), freq=100_000)   # MicroPython's default I2C0 pins on Pico boards
log = fglog.Log()


def wifi_connect(timeout_s=20):
    wlan = network.WLAN(network.WLAN.IF_STA)
    wlan.active(True)
    wlan.connect(secrets.WIFI_SSID, secrets.WIFI_PASS)
    t0 = time.time()
    while not wlan.isconnected():
        if time.time() - t0 > timeout_s:
            raise RuntimeError("Wi-Fi: no connection after %d s (status %d)" % (timeout_s, wlan.status()))
        led.toggle()
        time.sleep(0.25)
    led.off()
    print("Wi-Fi up, dashboard source at http://%s/data.json" % wlan.ifconfig()[0])
    return wlan


def read_sht45():
    i2c.writeto(fglog.SHT4X_ADDR, bytes([fglog.SHT4X_MEASURE_HI]))
    time.sleep_ms(10)                 # datasheet t_MEAS,h max 8.3 ms
    return fglog.sht4x_decode(i2c.readfrom(fglog.SHT4X_ADDR, 6))


async def sample_loop():
    while True:
        try:
            t, rh = read_sht45()
            print("logged", log.add(time.time(), t, rh))
        except (OSError, ValueError) as e:   # no ACK on the bus, or a CRC error
            print("sensor error:", e)
        led.on()
        await asyncio.sleep_ms(50)
        led.off()
        await asyncio.sleep(PERIOD_S)


async def main():
    wifi_connect()
    try:
        ntptime.settime()             # sets the RTC to UTC; rp2 counts time.time() from 1970-01-01
    except OSError as e:
        print("NTP failed, using board time:", e)
    await asyncio.start_server(lambda r, w: fglog.handle_http(r, w, log), "0.0.0.0", 80)
    await sample_loop()


asyncio.run(main())

Wi-Fi credentials go in secrets.py, which git ignores. Copy secrets.py.example and fill it in.

Back end

The dashboard needs only Python 3.12. The chart code draws one polyline per quantity and scales the axis to the data:

# target: host sdk: python tier: 2
"""Local dashboard for the Pico 2 W data logger. Standard library only.

Polls http://<pico>/data.json, keeps the history in memory and in a CSV file, and serves a page
with two inline SVG charts at http://127.0.0.1:8050/.
    python examples/pico2w-data-logger/host/dashboard.py --pico 192.168.1.42
"""
from __future__ import annotations

import argparse
import csv
import html
import json
import threading
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path


class History:
    def __init__(self, csv_path: Path | None = None) -> None:
        self.rows: dict[int, tuple[int, float, float]] = {}
        self.csv_path = csv_path
        self.lock = threading.Lock()
        self.last_error = ""

    def merge(self, doc: dict) -> int:
        """Add rows from one /data.json reply; returns how many were new."""
        idx = {name: i for i, name in enumerate(doc["fields"])}
        new = []
        with self.lock:
            for r in doc["rows"]:
                ts = int(r[idx["ts"]])
                if ts not in self.rows:
                    self.rows[ts] = (ts, float(r[idx["t_c"]]), float(r[idx["rh"]]))
                    new.append(self.rows[ts])
        if new and self.csv_path:
            first = not self.csv_path.exists()
            with self.csv_path.open("a", newline="") as fh:
                w = csv.writer(fh)
                if first:
                    w.writerow(["ts", "t_c", "rh"])
                w.writerows(sorted(new))
        return len(new)

    def sorted(self) -> list[tuple[int, float, float]]:
        with self.lock:
            return sorted(self.rows.values())


def poll_once(hist: History, url: str, timeout: float = 5) -> int:
    with urllib.request.urlopen(url, timeout=timeout) as r:
        return hist.merge(json.load(r))


def svg_line(points: list[tuple[float, float]], label: str, unit: str, w: int = 640, h: int = 180) -> str:
    """One small line chart as inline SVG. Axis range follows the data; no external libraries."""
    if len(points) < 2:
        return f"<p>{html.escape(label)}: waiting for data</p>"
    xs, ys = [p[0] for p in points], [p[1] for p in points]
    x0, x1 = min(xs), max(xs)
    y0, y1 = min(ys), max(ys)
    if y1 - y0 < 1e-6:
        y0, y1 = y0 - 0.5, y1 + 0.5
    pad = 32

    def sx(x: float) -> float:
        return pad + (x - x0) / (x1 - x0 or 1) * (w - 2 * pad)

    def sy(y: float) -> float:
        return h - pad - (y - y0) / (y1 - y0) * (h - 2 * pad)

    pts = " ".join(f"{sx(x):.1f},{sy(y):.1f}" for x, y in points)
    return (f'<svg viewBox="0 0 {w} {h}" width="100%" role="img" aria-label="{html.escape(label)}">'
            f'<text x="{pad}" y="16">{html.escape(label)} ({unit}), last {ys[-1]:.1f}</text>'
            f'<text x="2" y="{sy(y1) + 4:.1f}" font-size="11">{y1:.1f}</text>'
            f'<text x="2" y="{sy(y0) + 4:.1f}" font-size="11">{y0:.1f}</text>'
            f'<line x1="{pad}" y1="{h - pad}" x2="{w - pad}" y2="{h - pad}" stroke="#888"/>'
            f'<polyline fill="none" stroke="currentColor" stroke-width="2" points="{pts}"/></svg>')


def render(hist: History) -> str:
    rows = hist.sorted()
    t = svg_line([(r[0], r[1]) for r in rows], "Temperature", "°C")
    rh = svg_line([(r[0], r[2]) for r in rows], "Relative humidity", "%RH")
    when = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(rows[-1][0])) if rows else "never"
    err = f"<p>Last poll error: {html.escape(hist.last_error)}</p>" if hist.last_error else ""
    return ("<!doctype html><meta charset='utf-8'><meta http-equiv='refresh' content='30'>"
            "<title>Pico 2 W logger</title><body style='font-family:sans-serif;max-width:680px;margin:auto'>"
            f"<h1>Pico 2 W data logger</h1><p>{len(rows)} readings, newest {when}</p>{err}{t}{rh}</body>")

Run it with the Pico’s address, which main.py prints when Wi-Fi comes up:

python examples/pico2w-data-logger/host/dashboard.py --pico 192.168.1.42

Then open http://127.0.0.1:8050/ on the same computer. The page reloads every 30 s. The dashboard binds to 127.0.0.1 only, so other machines on the network cannot read it. The Pico’s own HTTP server has no authentication, so keep it on a network you trust.

Enclosure

There is no Field Guide enclosure for the Pico 2 W yet. The vented DevKit enclosure is drawn for the ESP32-C5-DevKitC-1 v1.2 and does not fit the Pico. A Pico 2 W design is a request to the Build backlog. The datasheet gives what such a design needs: a 51 mm × 21 mm × 1 mm board, four 2.1 mm (±0.05 mm) mounting holes, and an antenna at the bottom edge where no material should intrude. Until then, keep the SHT45 outside any box that holds the Pico, or in a separate vented compartment, so the board’s own warmth does not reach the reading.

Build and flash

cd examples/pico2w-data-logger/firmware
cp secrets.py.example secrets.py         # then edit it
mpremote cp fglog.py main.py secrets.py : + reset
mpremote repl                            # watch the console

main.py runs at every boot.

Test

What working looks like on the Pico’s console (values in angle brackets are your board’s):

Wi-Fi up, dashboard source at http://<ip>/data.json
logged (<unix time>, <t>, <rh>)

curl http://<ip>/data.json returns the document shown above, and the dashboard page shows a reading count and two charts.

  • Tier 1 (builds in CI): main.py and fglog.py compile with mpy-cross from MicroPython v1.29.0.
  • Tier 2 (runs in CI): firmware/test_fglog_unix.py runs on the MicroPython v1.29.0 Unix port. It checks the CRC against the datasheet example (CRC of 0xBEEF is 0x92), both conversions, rejection of a corrupted reply, log rotation with a 200-byte limit, and the HTTP handler through a real asyncio server on localhost. host/dashboard_test.py runs a fake Pico, polls it twice to prove duplicates are dropped, checks the CSV history and checks that the page has two charts.
  • Tier 3 (tested on hardware): waiting for the owner. The bench runner in tools/bench/ targets ESP-IDF boards, so this run uses MicroPython’s own tools:
mpremote connect <port> cp examples/pico2w-data-logger/firmware/fglog.py examples/pico2w-data-logger/firmware/main.py examples/pico2w-data-logger/firmware/secrets.py : + reset
curl http://<pico-ip>/data.json

The run passes when /data.json returns at least two rows a minute apart with temperatures and humidities in a plausible indoor range. The page shows tier 1, the lowest tier any part has reached, until that log is committed.

For makers

Get the dashboard working against the fake Pico in dashboard_test.py first if you like, then flash the board. Download /log.csv now and then: it is the full record, and it survives a power cut. If the Pico sits far from the access point, move it closer before you blame the code.

For product teams

An unauthenticated HTTP server on port 80 is fine on a bench and not in a product. Add TLS or keep the device behind a gateway, and give every unit its own credentials. Plan flash wear: rotation limits the size, not the number of writes, so batch writes if you sample faster. MicroPython builds are per board and per release, so pin the exact .uf2 you tested, as this page does.

Things to try

  • RISC-V cores. MicroPython v1.29.0 also publishes RPI_PICO2_W-RISCV-20260824-v1.29.0.uf2. The code has no Arm-specific parts. Run the same files and compare.
  • Lower power. Sleeping between samples saves energy on battery power. Measure first, with the current measurement method, so you know what the Wi-Fi connection costs before you change the code.
  • MQTT instead of HTTP. Publish each reading to the broker from the battery sensor project and let its logger and Home Assistant configuration do the rest.
  • More sensors. The SHT45 has one fixed address, 0x44. A second sensor of the same type needs the second I²C bus, I2C(1).

Summary

  • MicroPython v1.29.0 for the Pico 2 W (released 24 August 2026) runs a logger that samples an SHT45, keeps a rotating CSV on flash and serves JSON over Wi-Fi.
  • Board-independent logic sits in one module, tested on the MicroPython Unix port, so CI catches CRC, rotation and HTTP mistakes without a board.
  • The dashboard is standard-library Python, keeps its own history and is tested against a fake Pico.
  • There is no Pico 2 W enclosure yet. The datasheet’s outline, mounting holes and antenna keep-out are the inputs for one.