Skip to content

Electronic components: the DHT11 temperature and humidity sensor

This sensor is one of the first sensors you learn to use because everyone has a good application for it: building an indoor or outdoor thermometer.

Here you can see it mounted on a breakout board:

Note that the sensor has 4 output pins, although the breakout board I got only has 3 (the reason being the pin 3 of DHT11 is not connected to anything - don’t ask me why).

From the left, keeping our pins at the bottom, we have:

The output is a 40-bit serialized signal that lasts 4ms.

This means that every 4ms the sensor sends the temperature information and to read it we must get the value and unserialize it.

In the Arduino program we use the DHT Sensor Library maintained by Adafruit (here’s the link to the repository) that makes it very simple for us to read the temperature:

You include it with #include <DHT.h>, then you initialize an object of class DHT by passing the sensor signal pin and the type, in this case using the constant DHT11.

The library can also work with other sensors like the more precise DHT22 and DHT21

Then you can call the readHumidity() and readTemperature() methods to get values as a float variable.

readTemperature() gets the value as Celsius, but the library also provides a convertCtoF() method to get the Fahrenheit value.

The library also provide other methods, like computeHeatIndex(). I recommend you to checkout the DHT.h header file source code on GitHub.

This simple Arduino program reads the data from a DHT11 connected with the signal pin on digital pin #2 and prints it to the serial monitor:

#include <DHT.h>

DHT dht(2, DHT11);

void setup() {
  Serial.begin(9600);
  dht.begin();
}

void loop() {
  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t)) {
    Serial.println("Cannot read values");
    return;
  }

  Serial.println((String)"Humidity: " + h + "%, temperature: " + t + "C");
}

Humidity: 56.00%, temperature: 20.20C
Humidity: 56.00%, temperature: 20.20C
Humidity: 56.00%, temperature: 20.10C
Humidity: 56.00%, temperature: 20.20C

→ Here's my latest YouTube video

→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list