Complete Guide for DHT11/DHT22 Humidity and Temperature Sensor With Arduino

This article is a guide for the popular DHT11 and DHT22 temperature and humidity sensors with the Arduino. We’ll explain how it works, show some of its features and share an Arduino project example that you can modify to use in your own projects.

For more guides about other popular sensors, check our compilation of more than 60 Arduino tutorials and projects: 60+ Arduino Projects and Tutorials.

Introducing the DHT11 and DHT22 Sensors

The DHT11 and DHT22 sensors are used to measure temperature and relative humidity. These are very popular among makers and electronics hobbyists.

DHT11/DHT22 Temperature and Humidity Sensor using Arduino IDE

These sensors contain a chip that does analog to digital conversion and spit out a digital signal with the temperature and humidity. This makes them very easy to use with any microcontroller.

DHT11 vs DHT22

The DHT11 and DHT22 are very similar, but differ in their specifications. The following table compares some of the most important specifications of the DHT11 and DHT22 temperature and humidity sensors. For a more in-depth analysis of these sensors, please check the sensors’ datasheet.

DHT11
DHT22
Temperature range0 to 50 ºC +/-2 ºC-40 to 80 ºC +/-0.5ºC
Humidity range20 to 90% +/-5%0 to 100% +/-2%
ResolutionHumidity: 1%
Temperature: 1ºC
Humidity: 0.1%
Temperature: 0.1ºC
Operating voltage3 – 5.5 V DC3 – 6 V DC
Current supply0.5 – 2.5 mA1 – 1.5 mA
Sampling period1 second2 seconds
Price$1 to $5$4 to $10
Where to buyCheck pricesCheck prices

The DHT22 sensor has a better resolution and a wider temperature and humidity measurement range. However, it is a bit more expensive, and you can only request readings with 2 seconds interval.

The DHT11 has a smaller range and it’s less accurate. However, you can request sensor readings every second. It’s also a bit cheaper.

Despite their differences, they work in a similar way, and you can use the same code to read temperature and humidity. You just need to select in the code the sensor type you’re using.

DHT Pinout

DHT sensors have four pins as shown in the following figure. However, if you get your DHT sensor in a breakout board, it comes with only three pins and with an internal pull-up resistor on pin 2.

DHT22 Temperature and Humidity Sensor using Arduino IDE

The following table shows the DHT22 and DHT11 pinout. When the sensor is facing you, pin numbering starts at 1 from left to right

DHT pinConnect to
15V
2Any digital GPIO; also connect a 10k Ohm pull-up resistor
3Don’t connect
4GND

Where to buy?

You can check Maker Advisor Tools‘ page and find the best price for these modules:

DHT11 Temperature and Humidity Sensor with Arduino

In this section, we’ll build a simple project with the Arduino that reads temperature and humidity and displays the results on the Serial Monitor.

Parts Required

To complete this tutorial, you need the following components:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Schematic

Follow the next schematic diagram to wire the DHT11 (or DHT22) temperature and humidity sensor to the Arduino.

arduino dht11 wiring diagram_bb

Here are the connections (from left to right):

DHT PinArduino
Pin 1 5V
Pin 2D2 or any other digital pin
Pin 3 don’t connect
Pin 4GND

Note: if you’re using a module with a DHT sensor, it normally comes with only three pins. The pins should be labeled so that you know how to wire them. Additionally, many of these modules already come with an internal pull up resistor, so you don’t need to add one to the circuit.

Installing Libraries

To read from the DHT sensor, we’ll use the DHT library from Adafruit. To use this library you also need to install the Adafruit Unified Sensor library. Follow the next steps to install those libraries.

Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries. The Library Manager should open.

Search for “DHT” on the Search box and install the DHT library from Adafruit.

Installing Adafruit DHT library

After installing the DHT library from Adafruit, type “Adafruit Unified Sensor” in the search box. Scroll all the way down to find the library and install it.

Installing Adafruit Unified Sensor driver library

After installing the libraries, restart your Arduino IDE.

Code

After installing the necessary libraries, you can upload an example code from the library.

In your Arduino IDE, go to File > Examples > DHT Sensor library > DHTtester

The following code should load. It reads temperature and humidity, and displays the results in the Serial Monitor.

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11 
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600); 
  Serial.println("DHTxx test!");
 
  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);
  
  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);

  Serial.print("Humidity: "); 
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: "); 
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hi);
  Serial.println(" *F");
}

View raw code

How the Code Works

You start by including the DHT library:

#include "DHT.h"

Then, you define the pin that the DHT sensor is connected to. In this case it is connected to digital pin 2.

#define DHTPIN 2 // what digital pin we're connected to

Then, you need to define the DHT sensor type you’re using. In our example we’re using the DHT11.

#define DHTTYPE DHT11 // DHT 11

If you’re using another DHT sensor, you need to comment the previous line and uncomment one of the following:

//#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)

Then, initialize a DHT object called dht with the pin and type you’ve defined previously:

DHT dht(DHTPIN, DHTTYPE);

In the setup(), initialize the Serial Monitor at a baud rate of 9600 for debugging purposes.

erial.begin(9600);
Serial.println("DHTxx test!");

Initialize the DHT sensor with the .begin() method.

dht.begin();

In the loop(), at the beginning, there’s a delay of 2 seconds. This delay is needed to give enough time for the sensor to take readings. The maximum sampling rate is two seconds for the DHT22 and one second for the DHT11.

delay(2000);

Reading temperature and humidity is very simple. To get humidity, you just need to use the readHumidity() method on the dht object. In this case, we’re saving the humidity in the h variable. Note that the readHumidity() method returns a value of type float.

float h = dht.readHumidity();

Similarly, to read temperature use the readTemperature() method.

float t = dht.readTemperature();

Tto get temperature in Fahrenheit degrees, just pass true to the readTemperature() method as follows:

float f = dht.readTemperature(true);

This library also comes with methods to compute the heat index in Fahrenheit and Celsius:

// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);

Finally, all readings are displayed on the Serial Monitor.

Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");

Demonstration

After uploading the code to the Arduino, open the Serial Monitor at a baud rate of 9600. You should get sensor readings every two seconds. Here’s what you should see in your Arduino IDE Serial Monitor.

serial_monitor

Troubleshooting – Failed to read from DHT sensor

If you’re trying to read the temperature and humidity from the DHT11/DHT22 sensor and you get an error message in your Serial Monitor, follow the next steps to see if you can make your sensor work (or read our dedicated DHT Troubleshooting Guide).

“Failed to read from DHT sensor!” or Nan readings

If your DHT sensor returns the error message “Failed to read from DHT sensor!” or the DHT readings return “Nan”:

Solved Troubleshooting DHT11 DHT22 AM2302 AM2301 Failed to read from DHT sensor! or Nan

Try one of the following troubleshooting tips:

  • Wiring: when you’re building an electronics project, you need to double-check the wiring or pin assignment. After checking and testing that your circuit is properly connected, if it still doesn’t work, continue reading the next troubleshooting tips.
  • Power: the DHT sensor has an operating range of 3V to 5.5V (DHT11) or 3V to 6V (DHT22). If you’re powering the sensor from the a 3.3V pin, in some cases powering the DHT with 5V solves the problem.
  • Bad USB port or USB cable: sometimes powering the Arduino directly from a PC USB port is not enough. Try to plug it to a USB hub powered by an external power source. It might also help replacing the USB cable with a better or shorter one. Having a USB port that supplies enough power or using a good USB cable often fixes this problem.
  • Power source: as mentioned in the previous tip, your Arduino might not be supplying enough power to properly read from the DHT sensor. In some cases, you might need to power the Arduino with a power source that provides more current.
  • Sensor type: double-check that you’ve uncommented/commented in your code the right sensor for your project. In this project, we were using the DHT22:
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
  • Sampling rate: the DHT sensor is very slow getting the readings (the sensor readings may take up to 2 seconds). In some cases, increasing the time between readings solves the problem.
  • DHT sensor is fried or broken: unfortunately, these cheap sensors sometimes look totally fine, but they are fried/broken. So, even though you assembled the right circuit and code, it will still fail to get the readings. Try to use a different sensor to see if it fixes your problem.
  • Wrong baud rate or failed to upload code: if you don’t see anything in your Arduino IDE Serial Monitor double-check that you’ve selected the right baud rate, COM port or that you’ve uploaded the code successfully.

While building our projects, we’ve experienced similar issues with the DHT and it was always solved by following one of the methods described earlier.

Fatal error: Adafruit_Sensor.h: No such file or directory

There’s also a common error that happens when you try to compile the code. If you receive the following error:

fatal error: Adafruit_Sensor.h: No such file or directory 
#include <Adafruit_Sensor.h>

You need to install the Adafruit Unified Sensor driver library. In your Arduino IDE, type in the search box “Adafruit Unified Sensor“, scroll all the way down to find the library and install it.

Installing Adafruit Unified Sensor driver library

After installing the library, restart your Arduino IDE and the code should compile without the error message.

Wrapping Up

The DHT11 and DHT22 sensors provide an easy and inexpensive way to get temperature and humidity measurements with the Arduino. The wiring is very simple – you just need to connect the DHT data pin to an Arduino digital pin.

Writing the code to get temperature and humidity is also simple thanks to the DHT library. Getting temperature and humidity readings is as simple as using the readTemperature() and readHumidity() methods.

I hope you found this guide useful. Other guides with the DHT11/DHT22 temperature and humidity sensor:

If you like Arduino, you may also like the following resources:

Thanks for reading.

April 25, 2019



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

34 thoughts on “Complete Guide for DHT11/DHT22 Humidity and Temperature Sensor With Arduino”

  1. Real good. How about adding a transmitter/receiver to permit having the probe unit outside and read the data inside either on an iMAC computer or an LCD.

    (I can copy other people’s projects, but not so good at designing my own)

    Sincerely,

    Bob Pendergast

    Reply
    • That’s a good idea, it would be a nice addition to this project.
      Thanks for sharing,
      Rui

      P.S. You could use two arduino. One inside with a 433mhz receiver and the other Arduino outside with the humidity sensor+433mhz transmitter

      Reply
    • Hi RLPendergast,

      Easiest way is to hook it up to a ESP8266 (ESP-12 or similar) and use Arduino IDE for ESP8266. You can just run a small web server that dishes out the DHT info. I do it (currently d18b20) with an additional attached Relay so I can control heating. Pretty much done away with Arduinos for my projects. Too expensive total cost.

      Cheers Oliver

      Reply
  2. Thank you for the post. What about plotting a graph using the data available on serial monitor and send it wirelessly to the phone for viewing it using an app?
    Any idea on how to start on it?

    Reply
  3. Nice instructions! I prefer the (more expensive) DHT 22, as it is more accurate. Have it running now for a few months, outside, as part of my “weather-centre”. DHT 11 doesn’t cope very well when outside and high moisture…

    Reply
  4. hi rui how are u can u help me i want buy i2c ph board and i not found it i make ph meter by arduino and reading the value on pc can help me thanks for u ……
    mohammed

    Reply
  5. What is the purpose of the 10k resistor? I have built a freezer/refrigerator monitor and did not use them. It appears to work fine.

    Reply
    • Hey, Jonathan,
      If you want to connect more than one DHT (I think that is what you ask), you can easily do that: you take those lines in the sketch:
      // Initialize DHT sensor for normal 16mhz Arduino
      DHT dht(DHTPIN, DHTTYPE);
      And you can use DHT dht1(PIN1, DHT11), DHT dht2(PIN2, DHT11)… and so on. I used it with 2 x DHT22 sensors: one gives the outside temp and humidity, the other was the inside data.
      Works fine.

      Marc.

      Reply
  6. Thank for a great tutorial.

    I have installed DHT library and used a example ‘DHTTester’

    When I tried to compile, I’ve got the following error message…..
    but I don’t know how to solve the problem.

    Arduino: 1.8.5 (Windows 10), Board: “Arduino/Genuino Uno”

    In file included from C:\Users\Administrator\Documents\Arduino\libraries\DHT_sensor_library\DHT_U.cpp:22:0:

    C:\Users\Administrator\Documents\Arduino\libraries\DHT_sensor_library\DHT_U.h:25:29: fatal error: Adafruit_Sensor.h: No such file or directory

    #include

    ^

    compilation terminated.

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    Reply
  7. I have tried this method and several other libraries. I hoping this would be the one that worked. But still no go. I can hook up the DHT22 to my Arduino UNO and it reads Temp/Humidity just fine, but I cannot get the ESP8266-01 to read data. I get the “Failed to read from DHT sensor.” Any thoughts on why it works on the UNO but not on the EP8266? Thank you!

    Reply
    • Hi Al.
      Please check that the sensor is being properly powered (5V to the Vin pin of the sensor).
      Regards,
      Sara

      Reply
  8. The problem I’ve get was an unstable operation. The sketch loop block internally interrupted and operation started with printing DHTxx test! . That happened sporadically more or less frequently, sometimes normal reading doesn’t working, just a few lines printing with DHTxx test!.
    In my case the problem solved with adding small delays between sensor reading statements:
    void loop() {
    // Wait a few seconds between measurements.
    delay(2000);

    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds ‘old’ (its a very slow sensor)
    Serial.print(F(“Start to read: “));
    float h = dht.readHumidity(); Serial.print(F(” h, “));
    delay(250); // making readings form the sensor more sparce
    // Read temperature as Celsius (the default)
    float t = dht.readTemperature(); Serial.print(F(” t, “));
    delay(250); // making readings form the sensor more sparce
    // Read temperature as Fahrenheit (isFahrenheit = true)
    float f = dht.readTemperature(true); Serial.print(F(” f “));
    delay(250); // making readings form the sensor more sparce
    // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F(“Failed to read from DHT sensor!”));
    return;
    }
    //}

    // Compute heat index in Fahrenheit (the default)
    float hif = dht.computeHeatIndex(f, h); Serial.print(F(” Calculate hiV “));
    // Compute heat index in Celsius (isFahreheit = false)
    float hic = dht.computeHeatIndex(t, h, false); Serial.print(F(” Calculate hiC “));
    delay(1000); Serial.println(F(” Ready to print “));
    //Serial.println(F(“all are ready”));
    Serial.print(F(“Humidity: “));
    Serial.print(h);
    Serial.print(F(“% Temperature: “));
    Serial.print(t);
    Serial.print(F(“°C “));
    Serial.print(f);
    Serial.print(F(“°F Heat index: “));
    Serial.print(hic);
    Serial.print(F(“°C “));
    Serial.print(hif);
    Serial.println(F(“°F”));
    }

    One more unstable issue is delay() method operation. From time to time it starts to work with falce delay interval much less than requested by parameter of the method. Usually it turns into normal opreation after a few minutes ubnormality.

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.