© 2026 Hauntgears.com ("As an Amazon Associate I earn from qualifying purchases.")

Raspberry Pi Temperature Sensor Tutorial: Wiring And Code

Raspberry Pi Temperature Sensor Tutorial: Wiring And Code

Temperature drops are one of the most frequently reported indicators of paranormal activity. Cold spots can appear suddenly during investigations, and having reliable sensor data turns a subjective feeling into documented evidence. That’s exactly why this raspberry pi temperature sensor tutorial exists, to help you build a low-cost, customizable temperature monitoring tool that’s perfect for ghost hunting and environmental research alike.

A Raspberry Pi paired with a sensor like the DS18B20 or DHT11 gives you something most commercial devices don’t: full control over how data is collected, logged, and displayed. You choose the polling interval, the output format, and how the system alerts you to sudden changes. For paranormal investigators, that flexibility means you can build a dedicated cold-spot detector tailored to your exact field setup, something we appreciate here at Haunt Gears, where we spend our time testing and reviewing the gear that investigators actually depend on.

This guide walks you through the full process, from wiring your sensor to the Raspberry Pi’s GPIO pins to writing and running the Python code that reads temperature data. Whether you’re a beginner who’s never touched a breadboard or an experienced investigator looking to expand your DIY toolkit, each step includes clear diagrams and tested code snippets so you can get accurate readings on your first try.

What you need before you start

Getting this raspberry pi temperature sensor tutorial set up correctly starts with having the right parts on hand before you write a single line of code. Skipping the preparation step is the most common reason beginners stall midway through a build. Running through this checklist now will save you from discovering a missing resistor or an outdated OS image at a critical moment.

Hardware you’ll need

You don’t need a large parts budget to build this project. The core components are inexpensive and widely available through major electronics retailers, and most experienced makers already have the basics sitting in a parts bin. Here’s what to gather before you start wiring:

Hardware you'll need

Component Specification Notes
Raspberry Pi Model 3B, 3B+, 4, or Zero 2 W Any model with GPIO pins works
Temperature sensor DS18B20 (recommended) or DHT11 DS18B20 is more accurate and stable
4.7kΩ resistor Through-hole type Required pull-up for DS18B20 data line
Breadboard Half-size or full-size Simplifies wiring without soldering
Jumper wires Male-to-male and male-to-female At least 6 total
MicroSD card 8GB or larger, Class 10 Pre-loaded with Raspberry Pi OS
Power supply 5V 2.5A (Pi 3) or 5V 3A (Pi 4) Official Pi Foundation adapter recommended

The 4.7kΩ pull-up resistor is the part most beginners forget to order, and without it the DS18B20 data line won’t produce reliable readings. Pick up a handful of extras since they are tiny and easy to misplace on a busy workbench.

If you’re building this for paranormal field use, consider a waterproof DS18B20 probe variant. It handles moisture and lets you position the sensor several meters away from the Pi itself.

Software and OS setup

Before you run any Python code, your Raspberry Pi OS must be current and properly configured. If this is a fresh build, download the latest Raspberry Pi OS Lite or Desktop image from the official Raspberry Pi Foundation website and flash it to your microSD card using Raspberry Pi Imager. Once you boot the Pi and connect via monitor or SSH, run these two commands to update the system:

sudo apt update
sudo apt full-upgrade -y

After the update finishes, confirm that Python 3 is installed and working by running:

python3 --version

You should see output like Python 3.11.x. Current versions of Raspberry Pi OS ship with Python 3 pre-installed, so this is usually a quick confirmation rather than an installation step. If the command returns an error, install Python 3 with sudo apt install python3 -y and re-run the version check.

Skill level and time to complete

This project is designed for beginners, but it assumes a few baseline habits. You should be comfortable opening a terminal and typing commands. Prior Python experience is not required since every code block in this guide includes a full line-by-line explanation, but knowing how to navigate directories using cd and open a text editor will keep things moving.

Plan for 30 to 60 minutes on the full build the first time through, covering wiring, OS configuration, and your first live temperature reading. If you’re adding this sensor to an existing investigation rig rather than starting from scratch, the hardware wiring alone takes under 10 minutes once your parts list is confirmed and your Pi is already running an updated OS.

Choose the right sensor for your project

Two sensors cover the vast majority of use cases in this raspberry pi temperature sensor tutorial: the DS18B20 and the DHT11. Each has a different set of trade-offs, and picking the wrong one for your situation will create headaches down the line. Before you wire anything, spend two minutes with the comparison below to confirm which sensor matches your specific goals.

DS18B20: the better choice for most builds

The DS18B20 is a digital, single-wire sensor that communicates over the 1-Wire protocol, which means it only needs one GPIO data line to send readings back to your Pi. Its measurement range spans -55°C to +125°C with an accuracy of ±0.5°C between -10°C and +85°C, making it more than precise enough for cold-spot detection during a paranormal investigation. It also comes in a waterproof probe variant, so you can run the sensor cable through a wall or under a door to monitor remote areas without moving the Pi.

DS18B20: the better choice for most builds

If you’re planning to monitor multiple rooms simultaneously, you can chain up to 127 DS18B20 sensors on a single data wire, each with its own unique 64-bit serial address, so one Pi handles your entire location.

One hardware requirement you cannot skip is the 4.7kΩ pull-up resistor wired between the data pin and the 3.3V supply line. Without it, the 1-Wire bus stays in an undefined state and your readings will fail silently or return garbage values.

DHT11 and DHT22: when humidity matters

The DHT11 and DHT22 add humidity sensing on top of temperature, which makes them useful if you want to correlate environmental moisture with temperature changes. The DHT11 covers 0°C to 50°C with ±2°C accuracy, while the DHT22 extends that range to -40°C to 80°C with ±0.5°C accuracy, bringing it closer to DS18B20 performance.

Both DHT sensors require a minimum 2-second wait between readings, and they are more sensitive to electrical noise than the DS18B20. For a stationary investigation setup where you log data every few seconds, that delay is manageable. For a fast-polling alert system designed to catch brief cold spots, the DS18B20 is the stronger pick.

Sensor Temp Range Accuracy Humidity Protocol
DS18B20 -55°C to +125°C ±0.5°C No 1-Wire
DHT11 0°C to 50°C ±2°C Yes Single-wire
DHT22 -40°C to 80°C ±0.5°C Yes Single-wire

Step 1. Wire a DS18B20 to the Raspberry Pi

Correct wiring is the foundation of this entire raspberry pi temperature sensor tutorial. If the connections are wrong, your software will never work no matter how clean your Python code is. The DS18B20 uses only three pins, and the 4.7kΩ pull-up resistor between the data line and 3.3V is the one detail that trips up most first-time builders.

Understand the DS18B20 pin layout

Hold the DS18B20 with the flat face toward you and the three legs pointing down. From left to right, the pins are GND (ground), DQ (data), and VDD (power). Getting these reversed will either produce no readings or, in the worst case, generate enough heat to damage the sensor within seconds, so double-check before you apply power.

The waterproof probe version of the DS18B20 uses color-coded wires instead of physical pins: black for GND, yellow for DQ, and red for VDD.

Connect the sensor to the GPIO header

Place the DS18B20 in your breadboard so each leg sits in a separate column. Then run jumper wires from the breadboard to the Raspberry Pi’s GPIO header using the pin map below. GPIO 4 (physical pin 7) is the default 1-Wire data pin recognized by the Raspberry Pi OS kernel, so use that unless you have a specific reason to change it.

Connect the sensor to the GPIO header

DS18B20 Pin Connect to Pi Physical Pin
GND Ground rail Pin 6 (GND)
DQ (Data) GPIO 4 Pin 7 (GPIO4)
VDD 3.3V rail Pin 1 (3.3V)
4.7kΩ resistor Between DQ and VDD Bridges the two rails

Place the 4.7kΩ resistor so one leg lands in the same breadboard column as the DQ pin and the other leg lands in the same column as the VDD pin. This resistor pulls the data line high so the 1-Wire protocol can distinguish signal states reliably. Without it, the Pi sees a floating line and returns no data.

Once your wiring matches the table, visually trace each wire from the sensor to the Pi before you power anything on. Confirm that no bare wire legs are touching adjacent columns in the breadboard, which is the most common cause of short circuits on a crowded board. Power the Pi back up only after everything checks out.

Step 2. Enable 1-Wire on Raspberry Pi OS

The DS18B20 communicates over the 1-Wire protocol, which Raspberry Pi OS ships with disabled by default. No matter how clean your wiring is, the Pi will not detect the sensor until you turn on this interface. You can enable it in under two minutes using either the raspi-config menu tool or by editing the boot configuration file directly, and both methods produce the same result.

Enable 1-Wire through raspi-config

The fastest path to turning on 1-Wire support in this raspberry pi temperature sensor tutorial is through the built-in raspi-config utility. Open a terminal and run the following command:

sudo raspi-config

Navigate to Interface Options, then select 1-Wire, and confirm you want to enable it. The tool updates your boot configuration automatically. Once you exit raspi-config, reboot the Pi to apply the change:

sudo reboot

If you are running a headless Pi over SSH, raspi-config works exactly the same way through the terminal, so you do not need a monitor or keyboard attached to complete this step.

Enable 1-Wire by editing config.txt directly

If you prefer to skip the menu tool, you can add the 1-Wire overlay to your boot configuration file manually. This approach gives you direct visibility into what is being changed. Open the file with:

sudo nano /boot/firmware/config.txt

On older Raspberry Pi OS versions, the file lives at /boot/config.txt instead. Scroll to the bottom and add this single line:

dtoverlay=w1-gpio

Save the file with Ctrl+O, press Enter to confirm the filename, and exit with Ctrl+X. Reboot the Pi for the change to take effect.

Confirm the sensor is detected

After the Pi restarts, the kernel loads the w1-therm and w1-gpio modules automatically. Run these two commands to verify both modules are active:

lsmod | grep w1
ls /sys/bus/w1/devices/

The first command returns lines containing w1_gpio and w1_therm when everything is working. The second command lists every 1-Wire device on the bus, and your DS18B20 appears as a directory starting with 28- followed by its unique serial number. If the 28- directory is missing, power down the Pi, re-check your breadboard wiring, confirm the pull-up resistor bridges the DQ and VDD columns, and reboot to run the check again.

Step 3. Read DS18B20 temperature in Python

With 1-Wire enabled and your sensor confirmed on the bus, you’re ready to pull actual temperature data. The Raspberry Pi OS kernel handles all the low-level communication for you, exposing each DS18B20 reading as a plain text file inside the /sys/bus/w1/devices/ directory. Your Python script simply reads that file, parses the value, and prints the result. No third-party library installation is required for this step.

Locate the sensor’s data file

Before writing any code in this raspberry pi temperature sensor tutorial, confirm the exact path to your sensor’s raw data file. Run the following command, replacing the serial number with the 28- directory name you saw in Step 2:

cat /sys/bus/w1/devices/28-XXXXXXXXXXXX/w1_slave

The output will look like this:

50 05 4b 46 7f ff 0c 10 1c : crc=1c YES
50 05 4b 46 7f ff 0c 10 1c t=21312

The YES on the first line confirms a valid CRC check, meaning the reading is not corrupted. The value after t= on the second line is the temperature in millidegrees Celsius, so 21312 equals 21.312°C. Your Python script will target that t= value and convert it into a usable number.

Note the full path to your 28- directory now. You will paste it directly into the script below, and using the wrong path is the most common reason the script returns a FileNotFoundError on the first run.

Write and run the Python script

Open a new Python file on your Pi using nano read_temp.py and paste the following script. Every line includes an inline comment so you can follow exactly what the code does:


# read_temp.py - Read temperature from a DS18B20 sensor

import glob
import time

# Find the first connected DS18B20 device automatically
sensor_path = glob.glob('/sys/bus/w1/devices/28-*/w1_slave')[0]

def read_raw():
    # Open the sensor file and return all lines as a list
    with open(sensor_path, 'r') as f:
        return f.readlines()

def read_temperature():
    raw = read_raw()
    # Wait for a valid CRC before reading the temperature value
    while 'YES' not in raw[0]:
        time.sleep(0.2)
        raw = read_raw()
    # Extract the temperature value after 't='
    temp_string = raw[1].split('t=')[1]
    temp_c = float(temp_string) / 1000.0
    return temp_c

while True:
    temperature = read_temperature()
    print(f"Temperature: {temperature:.2f} °C")
    time.sleep(1)

Save the file with Ctrl+O, then run it using python3 read_temp.py. Your terminal will print a live temperature reading every second, and you can stop the loop at any time with Ctrl+C.

Step 4. Convert units and clean up the output

The script from Step 3 prints raw Celsius values, which works but isn’t particularly readable during a live investigation. This step in the raspberry pi temperature sensor tutorial shows you how to add a Fahrenheit conversion, round your values to a consistent decimal place, and format the output so it’s immediately useful when you’re scanning your terminal in a dark location.

Add Fahrenheit conversion

Your Python script already stores the Celsius reading in a variable, so converting to Fahrenheit takes one line of math. The standard formula is °F = (°C × 9/5) + 32, and you apply it directly inside the read_temperature function before the value is returned. Update your script so the function returns both values at once using a tuple:

def read_temperature():
    raw = read_raw()
    while 'YES' not in raw[0]:
        time.sleep(0.2)
        raw = read_raw()
    temp_string = raw[1].split('t=')[1]
    temp_c = float(temp_string) / 1000.0
    temp_f = (temp_c * 9 / 5) + 32
    return temp_c, temp_f

Update the main loop to unpack both return values and print them together:

while True:
    temp_c, temp_f = read_temperature()
    print(f"Temperature: {temp_c:.2f} °C  |  {temp_f:.2f} °F")
    time.sleep(1)

Running both units side by side eliminates the mental conversion step during a field investigation, which matters when you’re watching multiple data streams at once.

Format and label the output

Cleaner output is easier to scan, especially in low-light environments where you’re glancing at a screen between other tasks. Adding a timestamp to each printed line gives you a reference point if you notice a sudden drop and want to correlate it with audio or video footage captured at the same moment. Replace the print statement in your loop with this version:

from datetime import datetime

while True:
    temp_c, temp_f = read_temperature()
    now = datetime.now().strftime('%H:%M:%S')
    print(f"[{now}]  {temp_c:.2f} °C  |  {temp_f:.2f} °F")
    time.sleep(1)

Your terminal output will now look like this for every reading:

[21:43:07]  19.44 °C  |  66.99 °F
[21:43:08]  19.44 °C  |  66.99 °F
[21:43:09]  17.81 °C  |  64.06 °F

Each line carries a precise timestamp, both temperature units, and consistent spacing so the data reads cleanly whether you’re at a desk or reviewing a screenshot from the field later.

Step 5. Log readings to a file and plot trends

Printing live readings to the terminal is useful in the moment, but the data disappears the minute you close your session. Logging to a file lets you build a timestamped record across an entire investigation, which you can review afterward to spot patterns, sudden drops, or correlations with other captured evidence. This step in the raspberry pi temperature sensor tutorial extends your existing script to write every reading to a CSV file and then plot those readings as a line graph.

Write temperature readings to a CSV file

Python’s built-in csv module handles file logging without any extra installation. Open the file in append mode so each new run of your script adds lines to the existing record rather than overwriting previous data. Update your script to include the logging block shown below:

import csv
import glob
import time
from datetime import datetime

sensor_path = glob.glob('/sys/bus/w1/devices/28-*/w1_slave')[0]

def read_raw():
    with open(sensor_path, 'r') as f:
        return f.readlines()

def read_temperature():
    raw = read_raw()
    while 'YES' not in raw[0]:
        time.sleep(0.2)
        raw = read_raw()
    temp_string = raw[1].split('t=')[1]
    temp_c = float(temp_string) / 1000.0
    temp_f = (temp_c * 9 / 5) + 32
    return temp_c, temp_f

log_file = 'temperature_log.csv'

with open(log_file, 'a', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['timestamp', 'celsius', 'fahrenheit'])

    while True:
        temp_c, temp_f = read_temperature()
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        writer.writerow([now, f'{temp_c:.2f}', f'{temp_f:.2f}'])
        f.flush()
        print(f"[{now}]  {temp_c:.2f} °C  |  {temp_f:.2f} °F  (logged)")
        time.sleep(1)

The f.flush() call forces each row to write to disk immediately rather than waiting for the buffer to fill, which protects your data if the Pi loses power mid-investigation.

After a full investigation session, your CSV file gives you a precise timeline of every temperature event that happened in the room, sorted by the exact second it was recorded.

Plot the data with matplotlib

Once you have a populated CSV file, matplotlib turns your raw numbers into a visual trend line with just a few lines of code. Install matplotlib first by running pip3 install matplotlib in your terminal, then create a separate script called plot_temp.py:

Plot the data with matplotlib

import csv
import matplotlib.pyplot as plt

timestamps = []
celsius_readings = []

with open('temperature_log.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        timestamps.append(row['timestamp'])
        celsius_readings.append(float(row['celsius']))

plt.figure(figsize=(12, 5))
plt.plot(timestamps[::10], celsius_readings[::10], marker='o', linewidth=1)
plt.xticks(rotation=45, ha='right')
plt.xlabel('Time')
plt.ylabel('Temperature (°C)')
plt.title('Temperature Log - Investigation Session')
plt.tight_layout()
plt.savefig('temperature_trend.png', dpi=150)
plt.show()

The [::10] slice plots every tenth data point, which keeps the x-axis readable when you have hundreds of rows. Change that number to 1 if you want every single reading plotted instead. Running this script saves a PNG image of your trend graph to the same directory, ready to include in an investigation report alongside your audio and video files.

Troubleshooting and common gotchas

Even when you follow every step in this raspberry pi temperature sensor tutorial correctly, small wiring mistakes or misconfigured settings can produce confusing results. The issues below cover the most common problems builders run into, along with the specific fix for each one so you can get back to reading accurate data without digging through forum threads.

The sensor does not appear in /sys/bus/w1/devices/

This is the most frequently reported problem, and it almost always traces back to hardware rather than software. Start by powering down your Pi completely and checking each breadboard connection. Confirm that the 4.7kΩ pull-up resistor physically bridges the DQ column and the VDD column in the breadboard, not two empty columns. A resistor that is one column off looks correct to the eye but breaks the entire 1-Wire bus.

If your resistor legs are bent or touching adjacent metal contacts on the breadboard, you can short the data line and prevent the sensor from ever registering on the bus.

After verifying the wiring, check that dtoverlay=w1-gpio actually appears in your boot configuration file by running cat /boot/firmware/config.txt | grep w1. If the line is missing, the 1-Wire interface was never activated and the kernel modules will not load no matter how many times you reboot.

The script returns a FileNotFoundError

When Python cannot find the sensor path, the glob pattern in your script returned an empty list, meaning the 28- device directory does not exist at the moment the script runs. Confirm the sensor is detected first by running ls /sys/bus/w1/devices/ in the terminal before launching your script. If the directory appears there but the script still fails, check that you are running the script with python3 and not an older Python 2 binary, which handles glob differently.

Readings are inaccurate or jumping between values

Unstable readings usually point to electrical noise on the data line or a loose jumper wire that makes intermittent contact. Swap out the jumper wire connecting GPIO 4 to the DQ pin first, since those thin wires lose their grip in breadboard columns over time. If readings are consistently offset by a fixed amount rather than jumping, confirm your power supply is providing a stable 3.3V to the VDD pin. Using a GPIO pin that is set to output mode by another process on the same pin number will also corrupt 1-Wire communication, so verify no other scripts are claiming GPIO 4.

raspberry pi temperature sensor tutorial infographic

Quick recap and next steps

This raspberry pi temperature sensor tutorial covered every stage of the build: selecting the right sensor, wiring the DS18B20 with a pull-up resistor, enabling the 1-Wire interface, reading live data in Python, converting units, and logging readings to a CSV file you can graph and review after an investigation.

Your next move is to take this foundation further. Try adding a second DS18B20 on the same data wire to monitor two rooms simultaneously, or connect an LED that flashes when the temperature drops more than two degrees in under ten seconds. Both upgrades use the same wiring principles and Python patterns from this guide.

If you want purpose-built hardware alongside your DIY setup, check out the full range of paranormal investigation equipment at Haunt Gears. Professional-grade sensors and data loggers are available there to complement everything you just built.


Discover more from Haunt Gears

Subscribe to get the latest posts sent to your email.

More Posts

How to Document Ghost Evidence Properly
Insights for Investigators
Eric Windingstad

How to Document Ghost Evidence Properly

Learn how to document ghost evidence with a disciplined process, better logs, cleaner audio, and fewer false positives during investigations.

Read More »
Share via
Copy link