This project records the temperature every minute, around the clock, and shows it on a web page you can open on your phone. It's useful for a greenhouse, a loft, a garage, a fridge or a server cupboard. The readings are saved to a CSV file that opens in Excel or any spreadsheet. It uses a waterproof DS18B20 probe and about 100 lines of Python, using only what comes with Raspberry Pi OS.
What you need
- A Raspberry Pi, its power supply and a microSD card with Raspberry Pi OS
- A DS18B20 temperature sensor (the waterproof probe or the bare three-leg version)
- A 4.7 kΩ resistor (yellow, violet, red)
- A breadboard and three male-to-female jumper wires
Shopping list (7 items)
Some shop links are affiliate links (Amazon UK, Tooled Up): if you buy through one we may earn a small commission, at no extra cost to you. As an Amazon Associate I earn from qualifying purchases. It never changes which products we recommend, and no shop has paid to be included.
Everything for this build, in one place. Each link goes to a page we checked had the part in stock.
- 1×Raspberry Pi 5 (any memory size)Both Pi projects run on any Raspberry Pi with a 40-pin header, including a Pi 4 or Zero 2 W. The 8 GB Pi 5 is linked, but 2 or 4 GB is plenty here.
- 1×Raspberry Pi 27 W USB-C power supplyThe official supply for the Pi 5 (5 V, 5 A). A Pi 4 needs the 15 W supply instead.
- 1×microSD card, 32 GB, A1 ratedHolds Raspberry Pi OS and your files. A1 or A2 cards are quicker at the small reads and writes an operating system does.
- 1×DS18B20 waterproof temperature probeThis pack has three probes. The bare three-leg DS18B20 works the same way.
- 1×Resistor kit, 1/4 W (0.25 W) assorted valuesCovers every resistor in these projects.
- 1×Half-size breadboard (400 points)
- 1×Jumper wire kit (male-male, male-female and female-female)40 of each kind. Male-female wires go from a Raspberry Pi's pins to a breadboard.
- FreeRaspberry Pi ImagerWrites Raspberry Pi OS to the card. Nothing to buy.
Each button opens that shop's page for the part, checked when we wrote the list; if one shop is out of stock, try the next. Any equivalent part with the same value works.
The sensor
The DS18B20 is a digital thermometer from Analog Devices (originally Maxim). It measures from −55 °C to +125 °C and is accurate to ±0.5 °C from −10 °C to +85 °C, according to its datasheet. It uses the 1-Wire bus: one data wire, which needs a 4.7 kΩ pull-up resistor to 3.3 V. Raspberry Pi OS has a 1-Wire driver built in, so once it's turned on, the reading appears as a text file that Python can open like any other.
The circuit
| DS18B20 | Probe wire colour (usual) | Raspberry Pi |
|---|---|---|
| VDD | red | 3.3 V, physical pin 1 |
| Data (DQ) | yellow (sometimes white) | GPIO 4, physical pin 7 |
| GND | black | GND, physical pin 6 |
| 4.7 kΩ resistor | between the data wire and 3.3 V |
On the bare three-leg sensor, hold it with the flat face towards you and the legs down: the legs are GND, data and VDD from left to right. Probe colours vary between makers, so check the seller's listing. Power the sensor from 3.3 V: the Pi's GPIO pins are 3.3 V and a 5 V pull-up could damage them.
- Shut the Pi down and unplug it.
- Put the probe's three wires in three breadboard rows. Fit the 4.7 kΩ resistor between the data row and the 3.3 V row.
- Run male-to-female jumper wires from those rows to the Pi's pins 1, 7 and 6. Our Raspberry Pi pinout shows where they are.
Setting up the Pi
You need a Pi running Raspberry Pi OS that you can reach from your computer. Our Raspberry Pi first steps guide covers writing the card with Raspberry Pi Imager, turning on SSH and logging in. Raspberry Pi OS Lite, the version without a desktop, is enough for this project. Always unplug the Pi, or shut it down with sudo shutdown now, before changing the wiring.
Turn on 1-Wire
- Log in to the Pi and run
sudo raspi-config. - Choose Interface Options, then 1-Wire, then Yes. Finish and let it reboot.
- Log in again and run
ls /sys/bus/w1/devices/. You should see a name starting with28-, which is your sensor's unique serial number.
The program
Save this as temp_logger.py in your home folder, for example with nano temp_logger.py, then run it with python3 temp_logger.py. Open http://<your Pi's name>.local:8000 in a browser on the same network, using the name you gave the Pi when you set it up. The first reading appears within a minute.
# Temperature logger: reads a DS18B20 sensor every minute, saves each reading to temps.csv,
# and shows a web page at http://<your Pi's name>.local:8000 from any device on your network.
import csv
import glob
import threading
import time
from datetime import datetime, timedelta
from http.server import HTTPServer, BaseHTTPRequestHandler
SENSOR_GLOB = "/sys/bus/w1/devices/28-*/w1_slave"
LOG_FILE = "temps.csv"
EVERY = 60 # seconds between readings
PORT = 8000
latest = {"time": None, "temp": None}
def find_sensor():
found = glob.glob(SENSOR_GLOB)
if not found:
raise SystemExit("No DS18B20 found. Check the wiring and that 1-Wire is turned on.")
return found[0]
def read_temp(path):
for attempt in range(3):
with open(path) as f:
lines = f.read().splitlines()
# line 1 ends YES when the reading passed its check; line 2 ends t=<thousandths of a degree>
if len(lines) == 2 and lines[0].endswith("YES") and "t=" in lines[1]:
temp = int(lines[1].split("t=")[1]) / 1000
if temp != 85.0: # 85 °C is the sensor's power-on value, not a real reading
return temp
time.sleep(1)
return None
def logger(path):
while True:
temp = read_temp(path)
if temp is not None:
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
latest.update(time=now, temp=temp)
with open(LOG_FILE, "a", newline="") as f:
csv.writer(f).writerow([now, f"{temp:.2f}"])
time.sleep(EVERY)
def last_day():
try:
with open(LOG_FILE, newline="") as f:
rows = list(csv.reader(f))
except FileNotFoundError:
return []
since = datetime.now() - timedelta(hours=24)
return [(t, float(v)) for t, v in rows if datetime.strptime(t, "%Y-%m-%d %H:%M:%S") >= since]
class Page(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
day = last_day()
if latest["temp"] is None:
now_text = "<p>No reading yet. Refresh in a minute.</p>"
else:
now_text = f"<p class='big'>{latest['temp']:.1f} °C</p><p>at {latest['time']}</p>"
if day:
temps = [v for t, v in day]
now_text += f"<p>Last 24 hours: low {min(temps):.1f} °C, high {max(temps):.1f} °C</p>"
rows = "".join(f"<tr><td>{t}</td><td>{v:.1f} °C</td></tr>" for t, v in reversed(day[-10:]))
html = ("<!DOCTYPE html><html><head><meta charset='utf-8'>"
"<meta name='viewport' content='width=device-width, initial-scale=1'>"
"<meta http-equiv='refresh' content='60'><title>Temperature</title>"
"<style>body{font-family:sans-serif;margin:2em}.big{font-size:3em;margin:0}</style></head><body>"
f"<h1>Temperature</h1>{now_text}<table>{rows}</table>"
"<p><a href='/temps.csv'>Download all readings (CSV)</a></p></body></html>")
self.reply(200, "text/html; charset=utf-8", html.encode())
elif self.path == "/temps.csv":
try:
with open(LOG_FILE, "rb") as f:
self.reply(200, "text/csv", f.read())
except FileNotFoundError:
self.reply(200, "text/csv", b"")
else:
self.reply(404, "text/plain", b"Not found")
def reply(self, code, content_type, body):
self.send_response(code)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass # keep the terminal quiet
if __name__ == "__main__":
sensor = find_sensor()
threading.Thread(target=logger, args=(sensor,), daemon=True).start()
print(f"Logging to {LOG_FILE}. Open http://<your Pi's name>.local:{PORT}")
HTTPServer(("", PORT), Page).serve_forever()
How it works
- Reading the sensor. The driver writes two lines into a file called
w1_slave. The first ends inYESif the reading passed its check (a CRC), and the second ends int=followed by the temperature in thousandths of a degree, sot=18625means 18.625 °C. The program tries up to three times, and ignores 85 °C, which is the value the sensor holds before its first measurement and a classic sign of a power problem. - Two jobs at once. The logger runs in a background thread, waking once a minute to read and save, while the main program answers web requests. Our guide to CSV files in Python explains the file format.
- The web page. Python's built-in
http.serversends the latest reading, the low and high for the last 24 hours, and the last 10 readings. The page refreshes itself every minute./temps.csvdownloads every reading. - Tested. We ran this program against a simulated sensor file, including failed checks, the 85 °C value and missing readings, and fetched the page and the CSV from it to check the content.
Start it automatically
To start logging whenever the Pi boots, run crontab -e, choose an editor if it asks, and add this line at the bottom, changing yourname to your user name:
@reboot cd /home/yourname && /usr/bin/python3 temp_logger.py
Save, then reboot with sudo reboot. The cd makes sure temps.csv is saved in your home folder.
Troubleshooting
- "No DS18B20 found": 1-Wire isn't on, or the wiring is wrong. Check for the
28-folder as above. If it's missing, check the data wire is on GPIO 4 (physical pin 7) and the resistor is in place. - Readings stuck at 85 °C, or none at all: the sensor isn't getting proper power. Check the VDD and GND wires.
- The page doesn't open: check the address and port. If
.localnames don't work on your network, use the Pi's IP address, whichhostname -Ishows. - Long cables: 1-Wire works over several metres of cable, but very long runs may need a smaller pull-up resistor. Keep it simple and short to start with.
Take it further
- Add more probes on the same three wires. Each has its own
28-serial number, so change the program to read them all. - Plot a week of readings from the CSV file with Python, or open it in a spreadsheet.
- Make a Pico version that runs on a battery, using our Pico temperature logger project.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.