ESP32 DHT21 / AM2301A Temperature and Humidity Sensor
Overview
The DHT21 is a reliable sensor for measuring temperature and humidity, offering calibrated digital output and ease of integration with microcontrollers. With a temperature measurement range of -40°C to 80°C and a humidity range of 0% to 100%, the DHT21 is suitable for various applications, including environmental monitoring and HVAC systems.
About DHT21 / AM2301A Temperature and Humidity Sensor
The DHT21, also known as AM2301, is a digital temperature and humidity sensor that provides accurate environmental measurements. It uses a capacitive humidity sensor and a thermistor to ensure reliable data collection.
⚡ Key Features
- High Accuracy – Delivers precise temperature and humidity readings.
- Single-Wire Digital Communication – Easy integration with ESP32, Arduino, and other microcontrollers.
- Capacitive Humidity Sensing – Provides stable and long-term performance.
- Similar to DHT22 – Slight differences in casing and specifications.
With its ease of use and reliable performance, the DHT21 is ideal for climate monitoring, smart home systems, and industrial automation. 🚀
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 DHT21 pinout is as follows:
- Pin 1 (VCC): Connect to a 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
⚠️ Incorrect Temperature Readings
Issue: The DHT21 (AM2301A) sensor returns incorrect temperature values, such as 225°C.
Possible causes include incorrect sensor initialization or improper data handling in the code.
Solution: Ensure that the sensor is properly initialized in the code and that the correct data type is specified. Verify that the data reading and conversion logic accurately interpret the sensor's output. Refer to the sensor's datasheet for the correct data format and adjust the code accordingly.
💧 Humidity Reading Stuck at 99.9%
Issue: The DHT21 sensor consistently reports a humidity value of 99.9%, regardless of the actual environmental conditions.
Possible causes include sensor malfunction or environmental factors causing sensor saturation.
Solution: Ensure that the sensor is not exposed to conditions beyond its operational limits, such as high humidity or condensation. If the issue persists, consider replacing the sensor, as it may be defective.
❓ Receiving NaN (Not a Number) Values
Issue: The sensor intermittently returns NaN values for temperature or humidity readings.
Possible causes include unstable connections, lack of a pull-up resistor on the data line, or timing issues in data communication.
Solution: Verify that all connections are secure and that a pull-up resistor (typically 5kΩ) is connected between the data line and VCC. Ensure that the code accounts for the sensor's timing requirements, including appropriate delays between readings.
💻 Compilation Errors with DHT Library
Issue: Compilation errors occur when using the DHT library with the DHT21 sensor.
Possible causes include incorrect library version or improper library installation.
Solution: Ensure that the latest version of the DHT library is installed and correctly included in the project. Verify that the library supports the DHT21 sensor and that the correct sensor type is defined in the code.
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 DHT21 // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println("DHT21 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 DHT21 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: DHT21
temperature:
name: "Living Room Temperature"
humidity:
name: "Living Room Humidity"
update_interval: 60s
dht
platform. The pin
specifies the GPIO pin (e.g., GPIO4) where the sensor's DATA pin is connected. The model
is set to DHT21
to ensure correct data handling. Two sensors are configured: one for temperature and one for humidity, each with descriptive names such as 'Living Room Temperature' and 'Living Room Humidity.' The update_interval
is set to 60 seconds, meaning the sensor will provide new data 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 DHT21
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println("DHT21 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 DHT21 sensor
sensor = dht.DHT21(Pin(4))
print('DHT21 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 DHT21 sensor. The sensor is initialized on GPIO pin 4, and readings are taken every 2 seconds. The sensor.measure()
method updates the data, and sensor.temperature()
and sensor.humidity()
retrieve the temperature and humidity values, respectively. The results are printed to the console in a user-friendly format.Conclusion
The ESP32 DHT21 / AM2301A 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.