Skip to main content

Section 4.3 DHT 11 and DHT 22 temperature/humidity sensors

The DHT11 and DHT22 sensors are inexpensive digital sensors which measure both temperature and relative humidity. They are slowly being replaced by equivalent sensors with standard digital interfaces (I2C and SPI), but they are still widely available and easy to use.

The DHT22 is a fancier version of the DHT11; it gives more precise measurements and works over a wider temperature range (-40 to 80C, versus 0 to 50C for the DHT11).

Subsection 4.3.1 Wiring the DHT11

The DHT11 and DHT22 sensors have three pins, which should be connected as follows:

  • + connects to 3.3V

  • - connects to ground

  • out connects to any digital input pin

from machine import Pin

# DHT11 support is built in to MicroPython, just import the library:
from dht import DHT11

# Set up the sensor
# We're using pin 23, but any digital pin will work
inside = DHT11(Pin(23))

# Take a measurement from the sensor

# After we've taken a measurement, we can call the temperature() function
# to retrieve the actual temperature
degC = inside.temperature()
humidity = inside.humidity()

# Convert Celcius to Farenheit
degF = degC * 9.0 / 5.0 + 32
print(f"inside {degF} F  {humidity}% RH")

The DHT22 sensors work exactly the same way, except using DHT22 instead of DHT22. You'll need to change the import line to from dht import DHT22, and use DHT22() to set up the pin.

Subsection 4.3.2 Relative Humidity

The DHT11 and DHT22 sensors report relative humidity, which is the amount of water in the air relative to the maximum amount of water that the air can hold. This makes the relative humidity measurement highly dependent on temperature, since warm air can hold much more moisture than cold air.

Relative humidity is a useful measurement in meteorology; when the RH approaches 100%, water vapor will begin to condense on things (causing dew) and rain is likely. However, if you want to track the absolute humidity in an environment where the temperature is changing, you'll need to account for temperature swings. Conversion is not straightforward, but Wikipedia has a good table 1  to get you started.