CircuitPython DHT Sensor

DHT sensors are low cost humidity and temperature sensors with maker/beginner-level quality. Their simplicity makes them popular for many DIY projects. And you can use them with CircuitPython!

Wiring

DHT wiring is very simple:

  • The left-most pin is power. We recommend powering from 5V (sometimes 3V is not enough) - this is OK even if you are using 3.3V logic
  • The second pin is data. Connect a 10K pullup resistor from this pin to 3.3V. If you are using a DHT11 it's required. If you're using a DHT22 or AM2302 you can sometimes leave this off
  • Skip the third pin
  • The right-most pin is ground
For the DATA pin you must pick a pin that has PWM support (pulseio) - Check the board's guide for what pins have timers available

Here's an example using a Trinket M0 - you can use any CircuitPython board, just check that the Data pin is pulseio-capable.

You'll need the adafruit_dht library from the bundle so be sure that's installed, then you can run this code:

import board
import time
import adafruit_dht


dht  = adafruit_dht.DHT22(board.D2)

while True:
    try:
        temperature = dht.temperature
        humidity = dht.humidity
        # Print what we got to the REPL
        print("Temp: {:.1f} *C \t Humidity: {}% ".format(temperature, humidity))
    except RuntimeError as e:
        # Reading doesn't always work! Just print error and we'll try again
        print("Reading from DHT failure: ",e.args)

    time.sleep(1)

If you are using a DHT11, change the code to use a adafruit_dht.DHT11(board.D2) object.

Open the REPL to see the output! Breathe on the sensor to see it move temperature and humidity up (unless you are a White Walker in which case the temperature will go down)

Don't be concerned if once in a while you get an error, these sensors are pretty basic and sometimes the data transfer fails. The code will just try again!

Last updated on 2017-12-01 at 04.59.09 PM Published on 2017-07-26 at 06.08.30 PM