ESP32 DHT22 / AM2302 Temperature and Humidity Sensor
The DHT22 is a versatile and affordable sensor for measuring temperature and humidity. It provides calibrated digital output and is easy to interface with microcontrollers. With a temperature measurement range of -40°C to 80°C and humidity range of 0% to 100%, the DHT22 is suitable for a variety of applications, including environmental monitoring and HVAC systems.
Jump to Code Examples
Quick Links
DHT22 / AM2302 Price
About DHT22 / AM2302 Temperature and Humidity Sensor
The DHT22, also known as the AM2302, is a low-cost digital sensor for measuring temperature and humidity. It utilizes a capacitive humidity sensor and a thermistor to provide accurate readings. The sensor communicates over a single-wire digital interface, making it easy to integrate with microcontrollers like the ESP32. Compared to its predecessor, the DHT11, the DHT22 offers a wider measurement range and better accuracy, making it suitable for more demanding applications.DHT22 / AM2302 Sensor Technical Specifications
Below you can see the DHT22 / AM2302 Temperature and Humidity Sensor Technical Specifications. The sensor is compatible with the ESP32, operating within a voltage range suitable for microcontrollers. For precise details about its features, specifications, and usage, refer to the sensor’s datasheet.
- Protocol: Single-Wire Digital
- Operating Voltage: 3.3V to 5.5V
- Temperature Range: -40°C to 80°C
- Humidity Range: 0% to 100% RH
- Temperature Accuracy: ±0.5°C
- Humidity Accuracy: ±2% RH
- Sampling Rate: 0.5 Hz (once every 2 seconds)
- Dimensions: 15.1mm x 25mm x 7.7mm
DHT22 / AM2302 Sensor Pinout
Below you can see the pinout for the DHT22 / AM2302 Temperature and Humidity Sensor. The VCC
pin is used to supply power to the sensor, and it typically requires 3.3V or 5V (refer to the datasheet for specific voltage requirements). The GND
pin is the ground connection and must be connected to the ground of your ESP32!
The DHT22 pinout is as follows:
- Pin 1 (VCC): Connect to 3.3V or 5V power supply.
- Pin 2 (DATA): Outputs digital signal; connect to a digital input on your microcontroller.
- Pin 3 (NC): Not connected; leave unconnected.
- Pin 4 (GND): Connect to the ground of the microcontroller.
DHT22 / AM2302 Wiring with ESP32
Below you can see the wiring for the DHT22 / AM2302 Temperature and Humidity Sensor with the ESP32. Connect the VCC pin of the sensor to the 3.3V pin on the ESP32 or external power supply for power and the GND pin of the sensor to the GND pin of the ESP32. Depending on the communication protocol of the sensor (e.g., I2C, SPI, UART, or analog), connect the appropriate data and clock or signal pins to compatible GPIO pins on the ESP32, as shown below in the wiring diagram.
- Connect Pin 1 (VCC) to the 3.3V or 5V pin on the ESP32.
- Connect Pin 4 (GND) to the ground (GND) of the ESP32.
- Connect Pin 2 (DATA) to a digital GPIO pin on the ESP32 (e.g., GPIO 4).
- Place a 10kΩ pull-up resistor between the DATA pin and VCC to ensure reliable communication.
Code Examples
Below you can find code examples of DHT22 / AM2302 Temperature and Humidity Sensor with ESP32 in several frameworks:
ESP32 DHT22 / AM2302 Arduino IDE Code Example
Fill in your main
Arduino IDE sketch file with the following code to use the DHT22 / AM2302 Temperature and Humidity Sensor:
#include "DHT.h"
#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println("DHT22 Sensor Example");
dht.begin();
}
void loop() {
// Wait a few seconds between measurements
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
float humidity = dht.readHumidity();
// Read temperature as Celsius (the default)
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" % ");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
}
This Arduino sketch demonstrates how to interface with the DHT22 sensor. It initializes the sensor on digital pin 4 and reads the temperature and humidity every 2 seconds. The readings are then printed to the Serial Monitor. The code includes checks to ensure that the sensor readings are valid.
Connect your ESP32 to your computer via a USB cable, Ensure the correct Board and Port are selected under Tools, Click the "Upload" button in the Arduino IDE to compile and upload the code to your ESP32.
ESP32 DHT22 / AM2302 ESP-IDF Code ExampleExample in Espressif IoT Framework (ESP-IDF)
If you're using ESP-IDF to work with the DHT22 / AM2302 Temperature and Humidity Sensor, here's how you can set it up and read data from the sensor. Fill in this code in the main
ESP-IDF file:
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "dht.h"
#define DHT_PIN GPIO_NUM_4
void app_main() {
setDHTgpio(DHT_PIN);
while (1) {
printf("Reading DHT22 sensor...\n");
int ret = readDHT();
errorHandler(ret);
printf("Humidity: %.1f%%\n", getHumidity());
printf("Temperature: %.1f°C\n", getTemperature());
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}
This ESP-IDF example demonstrates how to read data from the DHT22 sensor using GPIO pin 4. The `readDHT()` function reads the sensor data, and the humidity and temperature values are retrieved using `getHumidity()` and `getTemperature()` functions, respectively. The readings are printed to the console every 2 seconds.
Update the I2C pins (I2C_MASTER_SDA_IO
and I2C_MASTER_SCL_IO
) to match your ESP32 hardware setup, Use idf.py build to compile the project, Use idf.py flash to upload the code to your ESP32.
ESP32 DHT22 / AM2302 ESPHome Code Example
Fill in this configuration in your ESPHome YAML configuration file (example.yml
) to integrate the DHT22 / AM2302 Temperature and Humidity Sensor
sensor:
- platform: dht
pin: GPIO4
model: DHT22
temperature:
name: "Living Room Temperature"
humidity:
name: "Living Room Humidity"
update_interval: 60s
The ESPHome configuration utilizes the `dht` platform to define the DHT22 sensor. The `pin` specifies the GPIO pin where the sensor's DATA pin is connected (e.g., GPIO4). The `model` is set to `DHT22` to ensure accurate data interpretation. Two sensor entities are defined: one for temperature and one for humidity, each assigned a user-friendly name like 'Living Room Temperature' and 'Living Room Humidity.' The `update_interval` is set to 60 seconds, meaning the sensor will update the readings every minute.
Upload this code to your ESP32 using the ESPHome dashboard or the esphome run
command.
ESP32 DHT22 / AM2302 PlatformIO Code Example
For PlatformIO, make sure to configure the platformio.ini
file with the appropriate environment and libraries, and then proceed with the code.
Configure platformio.ini
First, your platformio.ini
should look like below. You might need to include some libraries as shown. Make sure to change the board to your ESP32:
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
lib_deps =
adafruit/DHT sensor library @ ^1.4.2
monitor_speed = 115200
ESP32 DHT22 / AM2302 PlatformIO Example Code
Write this code in your PlatformIO project under the src/main.cpp
file to use the DHT22 / AM2302 Temperature and Humidity Sensor:
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println("DHT22 Sensor Example");
dht.begin();
}
void loop() {
// Wait a few seconds between measurements
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
float humidity = dht.readHumidity();
// Read temperature as Celsius (the default)
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" % ");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
}
This PlatformIO sketch demonstrates how to use the DHT22 sensor with an ESP32 board. It initializes the sensor on GPIO pin 4 and reads temperature and humidity data every 2 seconds. The results are printed to the Serial Monitor. The code includes checks to ensure the sensor data is valid, retrying if the readings are invalid.
Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload
command.
ESP32 DHT22 / AM2302 MicroPython Code Example
Fill in this script in your MicroPython main.py file (main.py
) to integrate the DHT22 / AM2302 Temperature and Humidity Sensor with your ESP32.
from machine import Pin
from time import sleep
import dht
# Initialize the DHT22 sensor
sensor = dht.DHT22(Pin(4))
print('DHT22 Sensor Example')
while True:
sensor.measure()
temperature = sensor.temperature() # Temperature in Celsius
humidity = sensor.humidity() # Relative Humidity in %
print('Temperature: {} °C'.format(temperature))
print('Humidity: {} %'.format(humidity))
sleep(2)
This MicroPython code uses the `dht` module to interact with the DHT22 sensor. It initializes the sensor on GPIO pin 4, reads temperature and humidity every 2 seconds, and prints the results to the console. The `sensor.measure()` function is used to fetch the data from the sensor, and the `temperature()` and `humidity()` methods are used to extract the values.
Upload this code to your ESP32 using a MicroPython-compatible IDE, such as Thonny, uPyCraft, or tools like ampy
.
Conclusion
We went through technical specifications of DHT22 / AM2302 Temperature and Humidity Sensor, its pinout, connection with ESP32 and DHT22 / AM2302 Temperature and Humidity Sensor code examples with Arduino IDE, ESP-IDF, ESPHome and PlatformIO.