Log temperature to a database with a live web chart on the Raspberry Pi

Turn the Raspberry Pi into a climate station that never forgets: a DHT11 sensor is read every minute, every reading goes into an SQLite database, and a Flask web page draws a live chart you can open on your phone....
  • Level:Advanced
  • Duration: 1 h 30 min
  • Ages 12+
  • Platform: Raspberry Pi

What you'll need

Log temperature to a database with a live web chart on the Raspberry Pi – EEMENTOR STEM™ lesson

Is your bedroom colder at night than you think? Does the bathroom stay damp for hours after a shower? A thermometer only tells you how warm it is right now. In this first advanced project, you build a climate station that remembers everything. The Raspberry Pi reads a DHT11 sensor every minute and stores each reading in a small database. A web page draws the last hours or days as a live chart that you can open on any phone on your Wi-Fi. At the end, you turn the program into a service that starts by itself every time the Pi boots, so it keeps logging without a screen, keyboard or you.

This path builds on the Raspberry Pi starter path. You should know how to wire an LED to a GPIO pin and run a Python program, and you have already met Flask in Control an LED from your phone with a Raspberry Pi web server.

What you'll learn

  • How to install Python libraries in a virtual environment on Raspberry Pi OS
  • How to read a DHT11 temperature and humidity sensor, and cope with missed readings
  • How to save data in an SQLite database and ask it questions with SQL
  • How to run a sensor loop and a web server at the same time with a thread
  • How to draw a live chart in the browser from JSON data
  • How to start a program automatically at boot with systemd

What you need

  • Raspberry Pi 4 Model B with Raspberry Pi OS on a microSD card (see the first starter lesson), its USB-C power supply, and a Wi-Fi connection
  • DHT11 temperature and humidity module (ESP32 IoT Starter Kit)
  • 1 LED and a 220 Ω resistor (ESP32 IoT Starter Kit)
  • Breadboard (ESP32 IoT Starter Kit)
  • Female-to-male jumper wires. If you don't have any, plug a female-female and a male-male Dupont wire from the ESP32 IoT Starter Kit together.
  • A phone, tablet or laptop on the same Wi-Fi network, to see the chart

Look after your Pi: the GPIO pins work at 3.3 V. Power the DHT11 module from a 3V3 pin, not 5V, so its data pin never sends more than 3.3 V into the Pi. Never connect a 3V3 or 5V pin to GND, and always shut the Pi down and unplug it before you change the wiring.

Wiring

The DHT11 module in the kit is the blue sensor on a small board with three pins, labelled S (signal), + and −. Some modules print the labels in a different order, so always follow the labels on your board. The module already has the pull-up resistor that the data line needs. The LED blinks briefly every time a reading is saved, so you can see that the logger is alive even without a screen.

Breadboard wiring diagram: DHT11 module S to GPIO 4 (pin 7), + to 3V3 (pin 1), minus to the minus rail; status LED with a 220 ohm resistor on GPIO 17 (pin 11); minus rail to GND (pin 9) on a Raspberry Pi 4.
Breadboard view. Check each connection against the wiring table below.
From To
DHT11 S GPIO 4 (pin 7)
DHT11 + 3V3 (pin 1)
DHT11 − The blue (−) rail
GPIO 17 (pin 11) 220 Ω resistor → LED long leg (+); LED short leg (−) → the blue (−) rail
The blue (−) rail GND (pin 9)

Step 1: Make a virtual environment and install the sensor library

Raspberry Pi OS protects its own Python. If you type pip install straight away, it stops with an externally-managed-environment error. The fix is a virtual environment: a folder with its own copy of Python where you can install anything you like. With --system-site-packages it can still use the libraries that came with Raspberry Pi OS, such as gpiozero and Flask. Open a Terminal and type:

sudo apt install python3-flask
python3 -m venv --system-site-packages ~/climate-env
source ~/climate-env/bin/activate
pip install adafruit-circuitpython-dht

The second-to-last line activates the environment: your prompt now starts with (climate-env). The last line installs Adafruit's DHT library together with Blinka, which lets it use the Pi's pins. Every time you open a new Terminal, run the source line again before you start the program.

Step 2: The program

Make a folder for the project with mkdir ~/climate, then create the program with a text editor, for example nano ~/climate/climate.py (or in Thonny, which you can point at the environment under Tools → Options → Interpreter). Paste the code and save it.

# Climate logger: DHT11 -> SQLite database -> live web chart (Flask)
import os
import sqlite3
import threading
import time
from datetime import datetime, timedelta

import adafruit_dht
import board
from flask import Flask, jsonify, request
from gpiozero import LED

FOLDER = os.path.expanduser("~/climate")
DB = os.path.join(FOLDER, "climate.db")
INTERVAL = 60                  # seconds between saved readings
os.makedirs(FOLDER, exist_ok=True)

led = LED(17)                  # blinks once for every saved reading
app = Flask(__name__)
sensor = None                  # created in main(), so tests can swap it


def connect():
    con = sqlite3.connect(DB)
    con.execute("CREATE TABLE IF NOT EXISTS readings ("
                "ts TEXT PRIMARY KEY, temp REAL, hum REAL)")
    return con


def read_sensor(tries=5):
    """Return (temperature, humidity), or None if the DHT11 keeps failing."""
    for _ in range(tries):
        try:
            t, h = sensor.temperature, sensor.humidity
            if t is not None and h is not None:
                return t, h
        except RuntimeError as err:      # the DHT11 misses a reading now and then
            print("Retrying:", err.args[0])
        time.sleep(2)                    # the DHT11 needs at least 1 s between reads
    return None


def save(t, h, when=None):
    when = when or datetime.now()
    with connect() as con:
        con.execute("INSERT OR REPLACE INTO readings VALUES (?, ?, ?)",
                    (when.strftime("%Y-%m-%d %H:%M:%S"), t, h))


def logger():
    while True:
        reading = read_sensor()
        if reading:
            save(*reading)
            led.blink(on_time=0.2, n=1)
            print(f"{datetime.now():%H:%M:%S}  {reading[0]:.0f} °C  {reading[1]:.0f} %")
        else:
            print("No reading this time")
        time.sleep(INTERVAL)


@app.route("/api/readings")
def readings():
    hours = request.args.get("hours", default=24, type=int)
    since = (datetime.now() - timedelta(hours=hours)).strftime("%Y-%m-%d %H:%M:%S")
    with connect() as con:
        rows = con.execute("SELECT ts, temp, hum FROM readings WHERE ts >= ? "
                           "ORDER BY ts", (since,)).fetchall()
    return jsonify([{"ts": ts, "temp": t, "hum": h} for ts, t, h in rows])


PAGE = """<!doctype html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Room climate</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<style>body{font-family:sans-serif;max-width:900px;margin:auto;padding:16px}
.now{font-size:2em;margin:8px 0}</style></head>
<body><h1>Room climate</h1>
<p class="now"><span id="t">--</span> °C &nbsp; <span id="h">--</span> %</p>
<p><select id="range"><option value="6">Last 6 hours</option>
<option value="24" selected>Last 24 hours</option><option value="168">Last 7 days</option></select></p>
<canvas id="chart"></canvas>
<script>
const chart = new Chart(document.getElementById("chart"), {type: "line",
  data: {labels: [], datasets: [
    {label: "Temperature (°C)", data: [], borderColor: "#DE544A", yAxisID: "t"},
    {label: "Humidity (%)", data: [], borderColor: "#1B3A7B", yAxisID: "h"}]},
  options: {pointRadius: 0, scales: {t: {position: "left"}, h: {position: "right", min: 0, max: 100}}}});
async function update() {
  const hours = document.getElementById("range").value;
  const rows = await (await fetch("/api/readings?hours=" + hours)).json();
  chart.data.labels = rows.map(r => r.ts.slice(5, 16));
  chart.data.datasets[0].data = rows.map(r => r.temp);
  chart.data.datasets[1].data = rows.map(r => r.hum);
  chart.update();
  if (rows.length) {
    document.getElementById("t").textContent = rows[rows.length - 1].temp.toFixed(0);
    document.getElementById("h").textContent = rows[rows.length - 1].hum.toFixed(0);
  }
}
document.getElementById("range").onchange = update;
update(); setInterval(update, 60000);
</script></body></html>"""


@app.route("/")
def home():
    return PAGE


def main():
    global sensor
    sensor = adafruit_dht.DHT11(board.D4)
    threading.Thread(target=logger, daemon=True).start()
    app.run(host="0.0.0.0", port=5000)


if __name__ == "__main__":
    main()

Start it from the Terminal, with the environment active:

cd ~/climate
python climate.py

Find the Pi's address with hostname -I in a second Terminal, then open http://<that address>:5000 in the browser on your phone, for example http://192.168.1.42:5000. Press Ctrl+C in the Terminal to stop the program.

What you should see

Every minute the Terminal prints the time, the temperature and the humidity, and the LED flashes once. Now and then you see a Retrying: line. That is normal for a DHT11: the program simply asks again two seconds later. The web page shows the latest values in big numbers and a chart with two lines, red for temperature and blue for humidity. Leave it running for an hour, breathe on the sensor or put it near a window, and watch the lines move. The chart updates itself every minute, and the menu above it switches between the last 6 hours, 24 hours and 7 days.

What you should see: the Terminal printing a temperature and humidity reading every minute with an occasional retry, and the Room climate web page with the latest values and a 24-hour chart of temperature and humidity.
One line per minute in the Terminal, and the history as a live chart on your phone.

How it works

How it works: the DHT11 sensor, the logger thread that reads it every 60 seconds, the SQLite readings table, and the Flask server that sends JSON to Chart.js in the browser; systemd starts the program at boot and restarts it after a crash.
Sensor → database → web page, started at boot by systemd.

The program has two jobs that must happen at the same time: reading the sensor once a minute, and answering the web browser at any moment. A thread solves this. threading.Thread(target=logger, daemon=True).start() runs the logger() loop in the background, while app.run() keeps the web server in the foreground. daemon=True means the thread stops when the program stops.

The DHT11 sends its 40-bit answer on one wire with very precise timing. Linux sometimes interrupts the Pi in the middle of a reading, and then the checksum doesn't match and the library raises a RuntimeError. read_sensor() catches it and tries up to five times, two seconds apart, because the sensor needs at least a second to get ready for the next reading.

Every good reading goes into SQLite, a complete database in a single file (climate.db). SQLite is built into Python, so there is nothing to install. The table has three columns: the time as text such as 2026-11-17 21:05:00, the temperature and the humidity. Because the times are written biggest unit first, comparing them as text also sorts them in time order. That is why WHERE ts >= ? finds every reading since a given moment. Each with connect() as con: block saves its changes automatically when it ends.

The page itself contains no readings. When it loads, its JavaScript asks /api/readings?hours=24, and Flask answers with a list in JSON, the same format phone apps use. Chart.js, a free charting library loaded from the jsDelivr CDN, turns that list into the chart. Because the data comes from its own address, you can also open /api/readings directly or use it from other programs.

Step 3: Start it automatically at boot

A logger is only useful if it keeps running after a power cut. systemd is the part of Linux that starts services when the Pi boots, and it restarts them if they crash. First find your user name with whoami. Then create a service file:

sudo nano /etc/systemd/system/climate.service

Paste this, replacing YOUR_NAME (three times) with your user name:

[Unit]
Description=Climate logger with web chart
After=network-online.target
Wants=network-online.target

[Service]
User=YOUR_NAME
WorkingDirectory=/home/YOUR_NAME/climate
ExecStart=/home/YOUR_NAME/climate-env/bin/python climate.py
Environment=PYTHONUNBUFFERED=1
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

Stop the program in the Terminal if it is still running, then switch the service on:

sudo systemctl daemon-reload
sudo systemctl enable --now climate.service
systemctl status climate.service

enable makes it start at every boot, and --now also starts it straight away. status should say active (running). Because ExecStart uses the Python inside your environment, you don't need to activate anything. To see the program's messages, type journalctl -u climate.service -f (Ctrl+C to leave). Now unplug the Pi, plug it back in and wait a minute: the web page comes back by itself, and the chart has a gap for the minutes the Pi was off.

Try this next

  • Add a third line to the chart with the Pi's own processor temperature, from gpiozero.CPUTemperature().temperature.
  • Show the lowest and highest temperature of the day under the big numbers, with SELECT MIN(temp), MAX(temp) FROM readings WHERE ts >= date('now', 'localtime').
  • Add a /download route that sends all readings as a CSV file you can open in a spreadsheet.
  • The next project adds a different kind of data to a database: who came through the door, and when.

Troubleshooting

  • error: externally-managed-environment: the environment isn't active. Run source ~/climate-env/bin/activate first.
  • Retrying: on every reading, or Timed out waiting for PulseIn message: check that S goes to GPIO 4 (pin 7) and + goes to 3V3. If it still fails, change the sensor line to adafruit_dht.DHT11(board.D4, use_pulseio=False), which reads the pin in a different way.
  • The page doesn't open on your phone: both must be on the same Wi-Fi, the address needs :5000 at the end, and it starts with http://, not https.
  • The page opens but the chart is empty: the first point appears after the first saved reading, so wait a minute. The chart also needs internet on your phone to load Chart.js.
  • The service fails to start: journalctl -u climate.service shows the error. Most often a path in the service file has a typo, or YOUR_NAME wasn't replaced everywhere.
  • The temperature looks a little high: the DHT11 is accurate to about ±2 °C, and the Pi itself gives off heat. Use longer wires to keep the sensor a few centimetres away from the Pi.

Next lesson

Build an RFID door with an attendance log on the Raspberry Pi: tap a card, the servo latch opens, and the Pi writes down who came in and when.