ESP32 DHT21 / AM2301A Temperature and Humidity Sensor
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.
Jump to Code Examples
Quick Links
DHT21 / AM2301A Price
About DHT21 / AM2301A Temperature and Humidity Sensor
The DHT21, also known as the AM2301, is a digital sensor designed for precise temperature and humidity measurements. It employs a capacitive humidity sensor and a thermistor to deliver accurate readings. Communicating via a single-wire digital interface, the DHT21 is straightforward to integrate with microcontrollers such as the ESP32. While it shares similarities with the DHT22 in terms of functionality, the DHT21 typically comes in a different casing and may have slight variations in specifications.DHT21 / AM2301A Sensor Technical Specifications
Below you can see the DHT21 / AM2301A 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: ±3% RH
- Sampling Rate: 0.5 Hz (once every 2 seconds)
- Dimensions: 59mm x 27mm x 13.5mm
DHT21 / AM2301A Sensor Pinout
Below you can see the pinout for the DHT21 / AM2301A 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 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.
DHT21 / AM2301A Wiring with ESP32
Below you can see the wiring for the DHT21 / AM2301A 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 DHT21 / AM2301A Temperature and Humidity Sensor with ESP32 in several frameworks:
ESP32 DHT21 / AM2301A Arduino IDE Code Example
Fill in your main
Arduino IDE sketch file with the following code to use the DHT21 / AM2301A Temperature and Humidity Sensor:
#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");
}
This Arduino sketch demonstrates how to interface with the DHT21 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 DHT21 / AM2301A ESP-IDF Code ExampleExample in Espressif IoT Framework (ESP-IDF)
If you're using ESP-IDF to work with the DHT21 / AM2301A 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 DHT21 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 DHT21 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 DHT21 / AM2301A ESPHome Code Example
Fill in this configuration in your ESPHome YAML configuration file (example.yml
) to integrate the DHT21 / AM2301A Temperature and Humidity Sensor
sensor:
- platform: dht
pin: GPIO4
model: DHT21
temperature:
name: "Living Room Temperature"
humidity:
name: "Living Room Humidity"
update_interval: 60s
The ESPHome configuration defines the DHT21 sensor using the `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.
Upload this code to your ESP32 using the ESPHome dashboard or the esphome run
command.
ESP32 DHT21 / AM2301A 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 DHT21 / AM2301A PlatformIO Example Code
Write this code in your PlatformIO project under the src/main.cpp
file to use the DHT21 / AM2301A Temperature and Humidity Sensor:
#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");
}
This PlatformIO code demonstrates interfacing the DHT21 sensor with an ESP32 board. It initializes the sensor on GPIO pin 4, reads the temperature and humidity values every 2 seconds, and outputs the data to the Serial Monitor. The code includes checks for invalid readings and retries if necessary.
Upload the code to your ESP32 using the PlatformIO "Upload" button in your IDE or the pio run --target upload
command.
ESP32 DHT21 / AM2301A MicroPython Code Example
Fill in this script in your MicroPython main.py file (main.py
) to integrate the DHT21 / AM2301A Temperature and Humidity Sensor with your ESP32.
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)
This MicroPython script uses the `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.
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 DHT21 / AM2301A Temperature and Humidity Sensor, its pinout, connection with ESP32 and DHT21 / AM2301A Temperature and Humidity Sensor code examples with Arduino IDE, ESP-IDF, ESPHome and PlatformIO.