AI & Agents

Raspberry Pi Temperature Sensor Guide: DS18B20 and DHT22 with OpenClaw

Raspberry Pi shipped 7.6 million units in 2025, and temperature sensing remains the most common first hardware project for new owners. This guide covers wiring both the DS18B20 and DHT22 sensors to a Pi, reading temperature with Python, and then building an OpenClaw agent that continuously monitors readings, detects anomalies, sends alerts, and logs historical data to a cloud workspace.

Fast.io Editorial Team 10 min read
An OpenClaw agent turns raw sensor readings into structured, searchable data.

Why Temperature Sensing Is Still the First Pi Project

Raspberry Pi Holdings shipped 7.6 million boards in 2025, a record driven partly by demand for edge computing and IoT prototyping. Temperature monitoring is the hardware equivalent of "hello world" for these boards, and for good reason: the DS18B20 costs under $5, needs three wires and a resistor, and produces calibrated digital output that requires no analog-to-digital converter.

Most existing tutorials stop at a Python script that prints readings to a terminal. That is fine for a weekend experiment, but it falls apart the moment you want continuous monitoring. Scripts crash, SD cards fill up with logs nobody reads, and there is no alerting when a freezer warms up at 3am or a greenhouse drops below frost thresholds.

This guide goes further. After covering the hardware wiring and Python fundamentals for both the DS18B20 and DHT22, it adds an OpenClaw agent that runs on the same Pi, interprets the data, sends alerts through messaging apps, and pushes structured logs to a cloud workspace where you can search them weeks later. The agent handles the parts that a static script cannot: trend detection, anomaly reasoning, and persistent storage that survives SD card failures.

DS18B20 vs DHT22 Sensor Comparison

Choosing between the DS18B20 and DHT22 depends on what you need to measure and where the sensor will live.

DS18B20

  • Protocol: 1-Wire (single GPIO pin for multiple sensors)
  • Temperature range: -55°C to +125°C
  • Accuracy: ±0.5°C (between -10°C and +85°C)
  • Resolution: configurable 9 to 12 bits (0.5°C down to 0.0625°C increments)
  • Humidity: not supported
  • Waterproof: available in a sealed stainless steel probe version
  • Sampling: as fast as 750ms at 12-bit resolution
  • Voltage: 3.0V to 5.5V
  • Multi-sensor: chain dozens on one GPIO pin, each addressed by a unique 64-bit serial

DHT22 (AM2302)

  • Protocol: proprietary single-wire (one sensor per GPIO pin)
  • Temperature range: -40°C to +80°C
  • Accuracy: ±0.5°C temperature, ±2% relative humidity
  • Resolution: 0.1°C temperature, 0.1% humidity
  • Humidity: 0% to 100% RH
  • Waterproof: not available in a sealed version
  • Sampling: one reading every 2 seconds minimum
  • Voltage: 3.3V to 6V
  • Multi-sensor: each sensor requires its own GPIO pin

When to pick each sensor. Use the DS18B20 for liquid temperature (brewing, aquariums, hydroponics), outdoor or harsh environments, or any project where you need multiple measurement points on one pin. Use the DHT22 when you need both temperature and humidity from a single device, such as a greenhouse, server room, or indoor climate monitor. You can also combine them: a DS18B20 probe in the liquid and a DHT22 for ambient air.

A performance comparison study published on ResearchGate found the DS18B20 achieved 99.05% accuracy against a reference thermometer, while the DHT22 reached 98.15%. Both are more than adequate for monitoring projects, but the DS18B20 edges ahead for precision-critical applications.

An AI agent sharing sensor data across a workspace

How to Wire and Read the DS18B20

The DS18B20 connects to the Pi with three wires and one resistor.

Wiring connections:

  • Red wire (VCC) to Pin 1 (3.3V) on the GPIO header
  • Black wire (GND) to Pin 6 (Ground)
  • Yellow wire (Data) to Pin 7 (GPIO 4), the default 1-Wire pin
  • 4.7k ohm pull-up resistor between GPIO 4 and 3.3V

The pull-up resistor is not optional. Without it, the 1-Wire bus floats and the sensor either returns garbage data or fails to respond entirely.

Enable 1-Wire on the Pi. Add this line to /boot/firmware/config.txt:

dtoverlay=w1-gpio

Reboot, then check for the sensor:

ls /sys/bus/w1/devices/

You should see a folder starting with 28- followed by the sensor's unique serial number. The temperature lives inside the w1_slave file in that folder.

Python reading script:

import glob
import time

base_dir = "/sys/bus/w1/devices/"
device_folder = glob.glob(base_dir + "28*")[0]
device_file = device_folder + "/w1_slave"

def read_temp():
    with open(device_file, "r") as f:
        lines = f.readlines()
    if lines[0].strip()[-3:] != "YES":
        return None
    pos = lines[1].find("t=")
    if pos == -1:
        return None
    temp_c = float(lines[1][pos + 2:]) / 1000.0
    return temp_c

while True:
    temp = read_temp()
    if temp is not None:
        print(f"{temp:.2f}°C")
    time.sleep(1)

Watch for false readings. The DS18B20 returns 85°C on power-up before its first conversion completes, and some drivers return 0°C on a read failure. Filter both values in production code.

Multiple sensors. Adding a second DS18B20 to the same GPIO 4 pin requires no additional wiring beyond the sensor itself. Each sensor appears as its own 28-* folder. This lets you measure, for example, pipe inlet and outlet temperatures with one data pin.

Fastio features

Give your sensor agent a workspace that outlasts the SD card

Fast.io's free tier includes 50GB of storage, built-in semantic search across your sensor logs, and MCP access for your OpenClaw agent. No credit card, no expiration.

How to Wire and Read the DHT22

The DHT22 uses a different protocol than the DS18B20 and requires its own GPIO pin per sensor.

Wiring connections:

  • Pin 1 (VCC) to 3.3V on the Pi
  • Pin 2 (Data) to any available GPIO pin (GPIO 17 is a common choice)
  • Pin 4 (GND) to Ground
  • 10k ohm pull-up resistor between VCC and the data pin

Pin 3 on the DHT22 is not connected. Some breakout boards include the pull-up resistor on the PCB, so check your module before adding an external one.

Install the Adafruit library:

pip install adafruit-circuitpython-dht
sudo apt install libgpiod2

Python reading script:

import adafruit_dht
import board
import time

dht = adafruit_dht.DHT22(board.D17)

while True:
    try:
        temp_c = dht.temperature
        humidity = dht.humidity
        if temp_c is not None:
            print(f"{temp_c:.1f}°C, {humidity:.1f}% RH")
    except RuntimeError:
        pass
    time.sleep(3)

The DHT22 protocol is timing-sensitive and occasionally returns checksum errors, which is why the except RuntimeError block exists. This is normal behavior, not a wiring problem. The library retries on the next read cycle. Set your polling interval to at least 2 seconds per the sensor's specification.

Humidity calibration note. The DHT22's ±2% humidity accuracy is factory-calibrated and cannot be adjusted. Over several years, the capacitive humidity element drifts. If you notice readings that seem consistently off, replace the sensor rather than applying correction factors in software.

An AI system analyzing and summarizing data logs

Building the OpenClaw Monitoring Agent

With the sensor wiring and Python scripts working, you can layer an OpenClaw agent on top to handle continuous monitoring, anomaly detection, and alerting.

OpenClaw runs directly on the Raspberry Pi. The Pi 5 with 8GB RAM is the tested and recommended model for OpenClaw, though a Pi 4 with 4GB handles simpler agent workloads. OpenClaw requires 64-bit Raspberry Pi OS.

Architecture. The sensor setup uses two layers. A deterministic Python script polls the sensor on a fixed interval (every 30 seconds is typical) and writes each reading to a local SQLite database with a timestamp and sensor serial number. The OpenClaw agent queries this database, interprets trends, and decides when to act. Splitting these layers means the sensor polling never depends on LLM response time, and the local database survives network outages.

What the agent handles:

  • Trend detection: the agent reads the last hour of data and identifies whether temperature is rising, falling, or stable. A sudden spike in a freezer or a slow drift in a greenhouse triggers different responses.
  • Anomaly filtering: raw DS18B20 readings of 85°C (power-on default) and 0°C (read failure) get flagged and excluded before analysis.
  • Threshold alerting: the agent sends notifications through Telegram, Discord, or email when temperature crosses configurable boundaries. Unlike a hard-coded threshold, the agent can distinguish between a brief door-open spike and a sustained warming trend.
  • Daily summaries: at a scheduled interval, the agent compiles min, max, average, and standard deviation for each sensor and pushes a structured report.

Storing data beyond the Pi. Local SQLite works for short-term buffering, but SD cards have limited write endurance, and the data dies if the card fails. The agent can push structured logs and daily summaries to a cloud workspace using the Fast.io MCP server. This gives you a searchable archive that outlasts the hardware. A Fast.io free agent account provides 50GB of storage and 5,000 monthly credits with no credit card required.

Other cloud storage options include pushing CSV files to S3, syncing a folder to Google Drive, or using InfluxDB Cloud for time-series data. Fast.io's advantage here is the built-in Intelligence Mode: once files land in a workspace, they are indexed for semantic search. You can ask "what was the coldest temperature last Tuesday?" across months of logs without writing a query.

Connecting OpenClaw to Fast.io. The Fast.io MCP server is accessible at the Streamable HTTP endpoint (/mcp) or the legacy SSE endpoint (/sse). The agent can upload files, create workspace folders, and query indexed data through the MCP toolset. Sensor logs become searchable workspace assets that any team member, or another agent, can access through the web UI or API without SSH access to the Pi.

Practical Applications and Troubleshooting

Temperature monitoring with an AI agent layer has applications well beyond the hobbyist bench.

Greenhouse and grow room automation. A DS18B20 measures soil or nutrient solution temperature while a DHT22 tracks air temperature and humidity. The agent correlates both readings, watches for conditions that promote mold (high humidity with warm temperatures), and can trigger ventilation fans through a relay. Logging to a cloud workspace lets you compare growing seasons and share environmental data with other growers.

Server room and network closet monitoring. Commercial environmental sensors for server rooms cost hundreds of dollars. A Pi with a DHT22 and an OpenClaw agent matches their core functionality at a fraction of the cost. The agent monitors both temperature and humidity, sends alerts when HVAC systems underperform, and maintains an audit trail of conditions. Store those logs in a Fast.io workspace and they become queryable by your ops team.

Cold chain and food safety. Restaurants, pharmacies, and labs need continuous temperature logging for compliance. A waterproof DS18B20 probe in a refrigerator or freezer, connected to an agent, produces timestamped records that satisfy inspection requirements. The agent flags excursions immediately rather than waiting for a manual check the next morning.

Multi-zone home monitoring. Chain several DS18B20 sensors on one GPIO pin to monitor different rooms, a crawl space, an attic, and an outdoor ambient point. The agent compares zones, detects anomalies (pipe freeze risk in the crawl space while the house is warm), and sends a single consolidated daily report.

Troubleshooting common issues:

  • Sensor not appearing in /sys/bus/w1/devices/: verify the dtoverlay=w1-gpio line in /boot/firmware/config.txt, confirm the pull-up resistor is connected, and check that the data wire is on GPIO 4 (Pin 7). A loose breadboard connection is the most common cause.
  • Readings stuck at 85°C: the DS18B20 has not completed its first temperature conversion. Add a 750ms delay after power-on before reading.
  • DHT22 returning frequent errors: the timing-sensitive protocol is vulnerable to kernel interrupts. Running fewer background processes on the Pi or increasing the polling interval to 5 seconds reduces errors.
  • SQLite database growing too large: configure the agent to roll over or compress data older than 30 days. Pushing historical data to cloud storage before local cleanup preserves the archive without filling the SD card.
  • Agent not connecting to Fast.io: verify network connectivity on the Pi and check that your API credentials are set. The MCP endpoint at /storage-for-agents/ requires authentication. Review the MCP documentation for current setup details.

Frequently Asked Questions

What temperature sensor works best with Raspberry Pi?

The DS18B20 is the most popular choice for temperature-only projects. It communicates over 1-Wire protocol on a single GPIO pin, supports chaining multiple sensors on that pin, and comes in a waterproof probe version for liquid measurements. If you also need humidity data, the DHT22 measures both temperature and relative humidity from one device. Both sensors cost under $10 and work with the Pi's 3.3V GPIO without level shifting.

How do I connect a DS18B20 to Raspberry Pi?

Connect the red wire to Pin 1 (3.3V), the black wire to Pin 6 (Ground), and the yellow data wire to Pin 7 (GPIO 4). Place a 4.7k ohm pull-up resistor between GPIO 4 and 3.3V. Enable the 1-Wire interface by adding `dtoverlay=w1-gpio` to `/boot/firmware/config.txt` and reboot. The sensor appears as a folder starting with `28-` in `/sys/bus/w1/devices/`.

Can Raspberry Pi measure room temperature?

Yes. A Raspberry Pi reads digital temperature sensors through its GPIO pins. The DS18B20 provides ±0.5°C accuracy across a -55°C to +125°C range. The DHT22 provides similar temperature accuracy plus humidity measurements. Connect either sensor to a GPIO pin, install the appropriate Python library, and read the sensor value in a few lines of code. No external ADC or complex circuitry is needed.

What is the difference between DS18B20 and DHT22?

The DS18B20 measures temperature only, supports the 1-Wire protocol (multiple sensors on one pin), has a wider temperature range (-55°C to +125°C), and is available in a waterproof probe. The DHT22 measures both temperature and humidity, requires a dedicated GPIO pin per sensor, has a narrower range (-40°C to +80°C), and samples no faster than once every 2 seconds. The DS18B20 is better for liquid or outdoor temperature. The DHT22 is better when you need humidity data alongside temperature.

Can I run multiple DS18B20 sensors on one Raspberry Pi?

Yes. The 1-Wire protocol allows dozens of DS18B20 sensors on a single GPIO pin. Each sensor has a unique 64-bit serial number, so the Pi addresses them individually. You only need one 4.7k ohm pull-up resistor for the entire bus. All sensors appear as separate `28-*` folders in `/sys/bus/w1/devices/`. This makes it practical to monitor multiple zones, such as different rooms, pipes, or tanks, from one Pi.

Does OpenClaw work with temperature sensors on Raspberry Pi?

OpenClaw runs on the Raspberry Pi and can interact with any sensor data accessible through shell commands or Python scripts. The recommended architecture uses a separate Python script to poll sensors and store readings in a local database, while the OpenClaw agent queries that database to analyze trends, detect anomalies, and trigger alerts. The agent can also push logs to cloud storage via MCP for long-term archival and team access.

Related Resources

Fastio features

Give your sensor agent a workspace that outlasts the SD card

Fast.io's free tier includes 50GB of storage, built-in semantic search across your sensor logs, and MCP access for your OpenClaw agent. No credit card, no expiration.