How to read DHT22 temperature + humidity on Raspberry Pi (Python)

Asked 1 week ago Modified 3 days ago Viewed 3 times
How to read DHT22 temperature + humidity on Raspberry Pi (Python)

Goal: get clean temperature + humidity readings from a DHT22 on a Raspberry Pi and log them to a CSV every 5 minutes for later graphing.

Why the Pi is harder than an Arduino: the DHT22 has a strict ~50µs timing protocol. Arduino can bit-bang it deterministically because nothing else is running. The Pi runs Linux, which can preempt your script mid-read. Solution: a tested library that retries on bad reads.

Parts

  • Raspberry Pi (any model with GPIO)
  • DHT22 sensor
  • 10kΩ pull-up resistor (some breakouts already have one — check)

Wiring

  • Pin 1 (VCC) → 3.3V (pin 1 on the Pi header)
  • Pin 2 (DATA) → GPIO4 (pin 7 on the header), with 10kΩ pull-up to 3.3V
  • Pin 4 (GND) → GND (pin 6)

Software setup

1. sudo apt update && sudo apt install -y python3-pip libgpiod2
2. pip3 install adafruit-circuitpython-dht
3. Test script (dht_test.py):

  import time, board, adafruit_dht
  dht = adafruit_dht.DHT22(board.D4)
  while True:
      try:
          t = dht.temperature
          h = dht.humidity
          print(f"{t:.1f}°C  {h:.1f}%")
      except RuntimeError as e:
          print('retry:', e)
      time.sleep(2)

Step 4 — Log to CSV. Wrap the read in a function, append a timestamped row to /home/pi/weather.csv every 5 minutes.
Step 5 — Visualise. Install Grafana + a simple SQLite/InfluxDB exporter, or open the CSV in LibreOffice and chart it.

Reliability tips

  • DHT22 needs at least 2 seconds between reads — don't poll faster.
  • Expect ~5% of reads to fail with 'RuntimeError'. Catch and retry; don't crash the script.
  • Run your script as a systemd service so it survives reboots. Create /etc/systemd/system/dht.service pointing at your .py file, then enable + start it.