This tutorial shows how to use the DHT11 and DHT22 temperature and humidity sensors with the ESP32 using Arduino IDE. We’ll go through a quick introduction to these sensors, pinout, wiring diagram, and finally the Arduino sketch.
Learn how to display temperature and humidity readings on a web server using the ESP32 or ESP8266 boards:
DHT11 and DHT22 Temperature and Humidity Sensors
The DHT11 and DHT22 sensors are used to measure temperature and relative humidity. These are very popular among makers and electronics hobbyists.
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.
If you’re looking to use these sensors with the Arduino board, you can read the following tutorial:
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.
Temperature range | 0 to 50 ÂșC +/-2 ÂșC | -40 to 80 ÂșC +/-0.5ÂșC |
Humidity range | 20 to 90% +/-5% | 0 to 100% +/-2% |
Resolution | Humidity: 1% Temperature: 1ÂșC | Humidity: 0.1% Temperature: 0.1ÂșC |
Operating voltage | 3 – 5.5 V DC | 3 – 6 V DC |
Current supply | 0.5 – 2.5 mA | 1 – 1.5 mA |
Sampling period | 1 second | 2 seconds |
Price | $1 to $5 | $4 to $10 |
Where to buy | Check prices | Check 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.
The following table shows the DHT22/DHT11 pinout. When the sensor is facing you, pin numbering starts at 1 from left to right
DHT pin | Connect to |
1 | 3.3V |
2 | Any digital GPIO; also connect a 10k Ohm pull-up resistor |
3 | Don’t connect |
4 | GND |
Parts Required
To follow this tutorial you need to wire the DHT11 or DHT22 temperature sensor to the ESP32. You need to use a 10k Ohm pull-up resistor.
Here’s a list of parts you need to build the circuit:
- ESP32 (read Best ESP32 development boards)
- DHT11 or DHT22 temperature and humidity sensor
- 10k Ohm resistor
- Breadboard
- Jumper wires
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 Diagram
Wire the DHT22 or DHT11 sensor to the ESP32 development board as shown in the following schematic diagram.
In this example, we’re connecting the DHT data pin to GPIO 4. However, you can use any other suitable digital pin.
Learn how to use the ESP32 GPIOs with our guide: ESP32 Pinout Reference: Which GPIO pins should you use?
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.
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.
After installing the libraries, restart your Arduino IDE.
ESP32 Reading Temperature and Humidity Sketch
To read temperature and humidity from the DHT sensor, we’ll use an example based on the Adafruit DHT library. Copy the following code to your Arduino IDE.
// Example testing sketch for various DHT humidity/temperature sensors written by ladyada
// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
#include "DHT.h"
#define DHTPIN 4 // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println(F("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 (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
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(F("Failed to read from DHT sensor!"));
return;
}
// 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);
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"));
}
There are many comments throughout the code with useful information. So, you might want to take a look at the comments. Continue reading to learn how the code works.
How the Code Works
First, you need to import the DHT library:
#include "DHT.h"
Then, define the digital pin that the DHT sensor data pin is connected to. In this case, it’s connected to GPIO 4.
#define DHTPIN 4 // Digital pin connected to the DHT sensor
Then, you need to select the DHT sensor type you’re using. The library supports DHT11, DHT22, and DHT21. Uncomment the sensor type you’re using and comment all the others. In this case, we’re using the DHT22 sensor.
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
Create a DHT object called dht on the pin and with the sensor type you’ve specified previously.
DHT dht(DHTPIN, DHTTYPE);
In the setup(), initialize the Serial debugging at a baud rate of 9600, and print a message in the Serial Monitor.
Serial.begin(9600);
Serial.println(F("DHTxx test!"));
Finally, initialize the DHT sensor.
dht.begin();
The loop() starts with a 2000 ms (2 seconds) delay, because the DHT22 maximum sampling period is 2 seconds. So, we can only get readings every two seconds.
delay(2000);
The temperature and humidity are returned in float format. We create float variables h, t, and f to save the humidity, temperature in Celsius and temperature in Fahrenheit, respectively.
Getting the humidity and temperature is as easy as using the readHumidity() and readTemperature() methods on the dht object, as shown below:
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
If you want to get the temperature in Fahrenheit degrees, you need to pass the true parameter as argument to the readTemperature() method.
float f = dht.readTemperature(true);
There’s also an if statement that checks if the sensor returned valid temperature and humidity readings.
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
After getting the humidity and temperature, the library has a method that computes the heat index. You can get the heat index both in Celsius and Fahrenheit as shown below:
// 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, print all the readings on the Serial Monitor with the following commands:
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"));
Demonstration
Upload the code to your ESP32 board. Make sure you have the right board and COM port selected in your Arduino IDE settings.
After uploading the code, open the Serial Monitor at a baud rate of 9600. You should get the latest temperature and humidity readings in the Serial Monitor every two seconds.
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”:
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 ESP32 3.3V pin, in some cases powering the DHT with 5V solves the problem.
- Bad USB port or USB cable: sometimes powering the ESP32 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 ESP might not be supplying enough power to properly read from the DHT sensor. In some cases, you might need to power the ESP 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.
After installing the library, restart your Arduino IDE and the code should compile without the error message.
Wrapping Up
With this tutorial you’ve learned how to get temperature and humidity readings from a DHT11 or DHT22 sensor using the ESP32 with Arduino IDE. Getting temperature and humidity readings with the Adafruit DHT library is very simple, you just use the readTemperature() and readHumidity() methods on a DHT object.
Now, you can take this project to the next level and display your sensor readings in a web server that you can consult using your smartphone’s browser. Learn how to build a web server with the ESP32 to display your sensor readings: ESP32 DHT11/DHT22 Web Server â Temperature and Humidity using Arduino IDE.
If you like ESP32, you may also like the following resources:
- Learn ESP32 with Arduino IDE (eBook + Video course)
- ESP32 Web Server â Arduino IDE
- ESP32 Web Server with BME280 â Mini Weather Station
- 20+ ESP32 Projects and Tutorials
We hope you’ve found this guide useful.
Thanks for reading.
What version of Arduino IDE are you using? I’m using 1.8.9 and I get the following error when compiling your code which I copied and pasted.
‘class DHT’ has no member named ‘computeHeatIndex’
Help please
Hi Alan.
Did you install the Adafruit DHT library?
Regards,
Sara
Hi, thanks. With this tutorial, it saves much time.
Thanks đ
I tested a DHT22 with a WROOM ESP32 for several days with not much success, just getting a lot of nan’s. I thought the sensors(2) were bad, but they worked fine installed on a nano. Then I thought the ESP32 was bad and I tried two with the same results. THEN, I finally followed your tutorial to a “T” including updating the adafruit dht library and INSTALLING the sensor unified library. Bazinga! everything works perfectly. I can’t tell you how much I appreciate you taking the time to put such a great tutorial online. I know it is a lot of work. Thanks again.
Hi Bruce!
Thank you so much for you nice words!
I’m really glad that you got your sensors working with our tutorial.
We always try to write our tutorials as complete and as easy to follow as possible, so that our readers can have their projects working on the first try.
Regards,
Sara đ
I coded one following this tutorial, working on the first upload. Great!!! Thank You.
Great!
Regards,
Sara
If you have problems reading the DHT sensors with the ESP 32 board, read my experience below.
I played with DHT sensors in the past with ESP 32. I do not remember I ran into any issues â except lately. I have no luck getting several of my ESP 32 boards to get a reading from the sensor. I didn’t try to find out what caused the problem.
Then I came across the DHTesp library – https://github.com/beegee-tokyo/DHTesp
The example is very complex because it utilizes the multi-core feature of the ESP 32. If you have an ESP 32 board, you only need to change the input PIN and the DHT type,
dht.setup(dhtPin, DHTesp::DHT22);
then you should be good.
I bust how the code should change when using two dht22 sensors connected to D2 and D4 thank you
Update: After I updated the “DHT-sensor-library” library. I am able to read the DHT sensor with ESP 32 with no issues. The current version of this library is 1.3.7.
Regards,
Hi, do you have this code also for Zerynth (Python language)?đ
Hi.
No.
We have for MicroPython: https://randomnerdtutorials.com/esp32-esp8266-dht11-dht22-micropython-temperature-humidity-sensor/
Regards,
Sara
Worked perfectly!
Thank you Sara…..
Great đ
Thanks for this great tutorial. It is a lot easier to follow than the Arduino samples.
Thanks đ
Great tutorial. Will this work with the ESP32 Huzzah Feather with the Esp32-Wroom-32?
Thank you.
Hi.
Yes. It should work.
Regards,
Sara
Hi, in my case just receive a lot of nan for both cases, i have espwroom32 and dht11
Hi.
See the DHT sensor troubleshooting guide: https://randomnerdtutorials.com/solved-dht11-dht22-failed-to-read-from-dht-sensor/
Regards,
Sara
It works pretty well as is.However it does NOT work in a RTOs environment. What should be edited??
how do i deal with serial monitor displaying unreadable characters
Hi.
Check your Serial Monitor baud rate.
Regards,
Sara
Hi.
How to send data from dht11 sensor to firebase using esp8266 ?
I would be really grateful if you can help.
Sorry, but what are you using to create the circuits?
Hello,
I have tried this but I always get a DHT error when I use a 10k ohm resistor. If I connect without a resistor I get values. The next problem the DHT sensor shows me values that are 3 degrees different than the real temperature. What can I do to fix this?
I found that the dht sensor has to be about 3 inches from the esp or my temps are higher because or the heat given off by the esp32.
Maybe the 10k is already built in to the dht sensor.
If the sensor is mounted on a small circuit board it probably has a small surface mount resistor on the circuit board already.
Just to say I found quite a simple workaround for what I believe to be a common problem – that of the DHTs crashing until the power is removed.
Rather than powering them from Vin I power them from another output pin – each pin is more than capable of driving a DHT of either type.
Depending on what the rest of your arduino is doing, you can then either power them up as and when you need them (bearing in mind you need a delay of a few seconds before they start reading) or just depower them and power them up again when ever you start getting bad readings.
Hope this helps someone.
Would one of you clever people mind explaining why its recommended to use an external pull-up resistor, rather than just using
pinMode(DHT_PIN, INPUT_PULLUP);
…please?
When I came to try this I realised that because you’re using a library rather than coding the DHT directly you don’t use a pinMode command, so there is no option to apply INPUT_PULLUP.
Oh well….
Apparently it’s working fine, but it seems to read a temperature a little too high (about 3 o 4 celsius degrees more). DHT11 with Wroom32 from az delivery.
I found that unless the dht11 was about 6 to 8 inches away from the esp32 the temperature readings were about 2 degrees higher. It was picking up the heat from the esp32 itself.
Hi,
I am new to arduino, i understood all the code you wrote, but one thing:
” if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F(“Failed to read from DHT sensor!”));
return; ”
in the above code what does the CAPTIAL F stands for ??
thank you for your time.
The pull up resistor is not needed, ESP32 has a built-in one for this pin.
You can enable it using:
pinMode (DHTPIN, INPUT_PULLUP);
CĂłmo podrĂa hacer para enviar los datos a un servidor en tiempo real y estos se puedan ver en una app, intentĂ© por firebase pero me dicen que actualizaron sus comunicaciones y ahora no funciona
Hi.
What exactly doesn’t work?
Firebase works for what you want to do
Regards,
Sara
I first tried with a DHT11 – temperature was OK but the humidity reading was fixed at 95% and would not vary. Some investigation on the internet explained that DHT11 humidity needs calibration and is not very accurate anyway.
My DHT11 was from ebay so it may be a fake.
I changed to a DHT22, altered DHTtype to DHT22 and now I get humidity readings that make sense.
I think I will only use DHT22 in the future, DHT11 is not worth the hassle.
I’m pretty sure I had exactly that issue with both DHT11 and DHT22. I was looking at some of the sensors which use the I2C port (which looks like it in theory solves a lot of the issues one has when running out of oddity-free I/o pins) but the wires run through the loft are only three-core and need to be 4 core for I2C.
Note that some of them can only run one device of an I2C bus, which does defeat the object a bit.
I found the length of the wire made a big difference. I was using a 22 awg wire that was 10m long and I was getting nan errors on 2/3rd of read attempts. When I shortened the wire to 5m the errors went away and I was getting 100% success on readings.
How do I tell if my dht11 is fried or not? I’m trying to get it to work but it only says “Failed to read from DHT sensor”.