← How-Tos
raspberry-pi Mar 26, 2026 ◯ 1 min read

Reading Temperature and Humidity with a DHT22 and Raspberry Pi

raspberry pidht22temperaturesensor

The DHT22 is a cheap, accurate temperature and humidity sensor. Here's wiring and code for the Raspberry Pi.

DHT11 vs DHT22

SensorTemp AccuracyRangeCost
DHT11+-2 degrees C0-50C~$1
DHT22+-0.5 degrees C-40-80C~$3

Use DHT22 โ€” the accuracy difference is worth it.

Wiring

DHT22 PinRaspberry Pi
VCC3.3V
DATAGPIO4
GNDGND

Add a 10k ohm pull-up resistor between DATA and VCC.

Installation

pip install adafruit-circuitpython-dht
sudo apt install libgpiod2

Python Code

import adafruit_dht
import board, time

dht = adafruit_dht.DHT22(board.D4)

while True:
    try:
        temp = dht.temperature
        humidity = dht.humidity
        print(f"Temp: {temp:.1f}C  Humidity: {humidity:.1f}%")
    except RuntimeError as e:
        print(f"Read error: {e}")  # occasional errors are normal
    time.sleep(2)  # DHT22 needs 2s between reads

Logging to CSV

import csv
from datetime import datetime

with open('readings.csv', 'a', newline='') as f:
    writer = csv.writer(f)
    writer.writerow([datetime.now().isoformat(), temp, humidity])