This tutorial uses the Arduino IDE to demonstrate how to use the DHT11 and DHT22 temperature and humidity sensors with the ESP32. We’ll go through a basic overview of these sensors, as well as pinouts, wire diagrams, and the Arduino sketch.
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
- DHT11 or DHT22 temperature and humidity sensor– The DHT11 is a basic, ultra low-cost digital temperature and humidity sensor. It uses a capacitive humidity sensor and a thermistor to measure the surrounding air, and spits out a digital signal on the data pin.The DHT22 is the more expensive version which obviously has better specifications. Also the DHT22 sensor has better humidity measuring range, from 0 to 100% with 2-5% accuracy, while the DHT11 humidity range is from 20 to 80% with 5% accuracy.
- 10k Ohm resistor
- Breadboard
- Jumper wires
Introduction to 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.
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 |
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.
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
#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")); }
How 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 must choose the DHT sensor type you want to use. DHT11, DHT22, and DHT21 are supported by the library. Remove the sensor type you’re using and leave the others alone. We’re using the DHT22 sensor in this case.
//#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);
In float format, the temperature and humidity are returned. To save the humidity, temperature in Celsius, and temperature in Fahrenheit, we construct float variables h, t, and f.
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: You should double-check the wiring or pin assignment when developing an electronics project. If your circuit still doesn’t work after checking and ensuring that it is properly connected, continue reading the next troubleshooting recommendations.
- Power: The operational range of the DHT sensor is 3V to 5.5V (DHT11) or 3V to 6V (DHT12) (DHT22). If you’re using the ESP32’s 3.3V pin to power the sensor, you may find that switching to 5V solves the problem.
- Bad USB port or USB cable: Occasionally, directly powering the ESP32 from a PC USB port is insufficient. Try connecting it to a USB hub with an external power supply. It may also be beneficial to replace the USB cable with a more suitable or shorter one. This problem is frequently resolved by having a USB port with sufficient power or by using a decent USB connection.
- Power source: Your ESP may not be supplying enough power to adequately read from the DHT sensor, as described in the preceding article. In some circumstances, you may need to supply the ESP with a higher-current power source.
- 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.
CONCLUSION
We learnt how to use the ESP32 with Arduino IDE to get temperature and humidity measurements from a DHT11 or DHT22 sensor in this article. The readTemperature() and readHumidity() methods on a DHT object are all you need to get temperature and humidity data with the Adafruit DHT library.