ESP32 DHT22 / AM2302 Temperature and Humidity Sensor
Overview
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.
About DHT22 / AM2302 Temperature and Humidity Sensor
The DHT22, also known as AM2302, is a low-cost digital sensor designed for precise temperature and humidity measurement. It uses a capacitive humidity sensor and a thermistor for reliable data collection and communicates via a single-wire digital interface, ensuring easy integration with ESP32, Arduino, and other microcontrollers.
⚡ Key Features
- Improved Accuracy & Range – More precise than DHT11, with a wider measurement range.
- Single-Wire Communication – Simple interfacing with microcontrollers.
- Capacitive Humidity Sensing – Ensures stable and long-term performance.
- Ideal for Demanding Applications – Used in weather stations, HVAC systems, and industrial monitoring.
With its affordability and high accuracy, the DHT22 is a great choice for climate monitoring and smart home applications. 🚀
Where to Buy
Prices are subject to change. We earn from qualifying purchases as an Amazon Associate.
Technical Specifications
Pinout Configuration
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.
Wiring with ESP32
- 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.
Troubleshooting Guide
Common Issues
❌ Failed to Read from DHT Sensor
Issue: Receiving 'Failed to read from DHT sensor!' or NaN readings when attempting to retrieve data from the DHT22 (AM2302) sensor.
Possible causes include incorrect wiring, insufficient power supply, or improper sensor initialization.
Solution: Double-check the wiring connections: ensure VCC is connected to 3V to 6V, GND to ground, and the data pin to the appropriate GPIO pin on the microcontroller. Verify that a suitable pull-up resistor (typically 5kΩ) is connected between the data pin and VCC. Ensure the sensor is properly initialized in the code, and that the correct sensor type is specified in the library. Additionally, consider increasing the time between sensor readings, as the DHT22 has a sampling rate of once every 2 seconds.
❄️ Incorrect Readings at Sub-Zero Temperatures
Issue: The DHT22 sensor provides incorrect temperature readings when the ambient temperature falls below 0°C (32°F).
Possible causes include limitations in the sensor's design or firmware that affect accuracy at low temperatures.
Solution: Be aware that the DHT22 may have reduced accuracy at temperatures below freezing. For applications requiring precise measurements in sub-zero conditions, consider using a sensor specifically designed for low-temperature accuracy.
⏸️ Sensor Stops Responding After Prolonged Use
Issue: The DHT22 sensor ceases to provide valid readings after extended periods of operation, requiring a reset to resume functionality.
Possible causes include sensor lockup due to environmental factors or power supply instability.
Solution: Implement periodic sensor resets in your code to mitigate potential lockups. Ensure a stable power supply and consider adding decoupling capacitors to filter out noise. If the problem persists, evaluate the operating environment for factors that may adversely affect the sensor's performance.
⚡ Interference with Other I2C Devices
Issue: Connecting the DHT22 sensor alongside other I2C devices causes communication issues or device malfunctions.
Possible causes include the DHT22's communication protocol conflicting with I2C devices.
Solution: The DHT22 uses a proprietary single-wire protocol and does not operate on the I2C bus. Ensure that the sensor is connected to a dedicated GPIO pin and that its communication does not interfere with I2C devices. If issues persist, consider isolating the sensor's data line from the I2C bus.
Debugging Tips
🔍 Serial Monitor
Use the Serial Monitor to check for error messages and verify the sensor's output. Add debug prints in your code to track the sensor's state.
⚡ Voltage Checks
Use a multimeter to verify voltage levels and check for continuity in your connections. Ensure the power supply is stable and within the sensor's requirements.
Additional Resources
Code Examples
Arduino Example
#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");
}
ESP-IDF Example
#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);
}
}
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.ESPHome Example
sensor:
- platform: dht
pin: GPIO4
model: DHT22
temperature:
name: "Living Room Temperature"
humidity:
name: "Living Room Humidity"
update_interval: 60s
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.PlatformIO Example
platformio.ini
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
lib_deps =
adafruit/DHT sensor library @ ^1.4.2
monitor_speed = 115200
PlatformIO Example Code
#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");
}
MicroPython Example
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)
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.Conclusion
The ESP32 DHT22 / AM2302 Temperature and Humidity Sensor is a powerful environment sensor that offers excellent performance and reliability. With support for multiple development platforms including Arduino, ESP-IDF, ESPHome, PlatformIO, and MicroPython, it's a versatile choice for your IoT projects.
For optimal performance, ensure proper wiring and follow the recommended configuration for your chosen development platform.
Always verify power supply requirements and pin connections before powering up your project to avoid potential damage.