ESP32 DHT22 Temperature & Humidity Sensor Tutorial
- Get link
- X
- Other Apps
ESP32 DHT22 Temperature & Humidity Sensor Tutorial (With Code & Wiring Diagram)
Meta description: Learn how to connect a DHT22 sensor to an ESP32 and read temperature and humidity data with this complete wiring diagram, code, and troubleshooting guide.
Introduction
The DHT22 is one of the most popular sensors for measuring temperature and humidity in DIY electronics and IoT projects. Paired with an ESP32 — a microcontroller with built-in Wi-Fi and Bluetooth — it's a great starting point for weather stations, home automation systems, or any project that needs environmental data.
This guide walks through wiring the DHT22 to an ESP32, writing the code to read sensor data, and displaying temperature and humidity readings on the Serial Monitor.
What This Project Does
You'll build a simple circuit where the ESP32 reads temperature (in Celsius and Fahrenheit) and humidity from a DHT22 sensor, then prints the readings to the Serial Monitor every few seconds.
This is the foundation for more advanced projects like web-based dashboards, data logging, or automated fan/heater control.
Required Components
- ESP32 development board
- DHT22 temperature and humidity sensor (also works with DHT11, with minor code changes)
- 10kΩ resistor (pull-up resistor — some DHT22 breakout modules already include this)
- Breadboard
- Jumper wires
- Micro-USB cable
Features
- Reads both temperature and humidity from a single sensor
- Displays readings in both Celsius and Fahrenheit
- Simple, beginner-friendly wiring with only 3 connections
- Easily expandable into a web server or data logger later
How It Works
The DHT22 communicates with the ESP32 over a single digital data line using a timing-based protocol.
The Adafruit DHT sensor library handles all the low-level timing so you don't need to decode the protocol manually — you just call a function and get back a temperature or humidity value.
Wiring / Circuit Information
Connect the DHT22 to the ESP32 as follows:
| DHT22 Pin | ESP32 Pin |
|---|---|
| VCC (+) | 3.3V |
| DATA (out) | GPIO 4 |
| GND (-) | GND |
If you're using a bare DHT22 sensor (not a breakout module), add a 10kΩ pull-up resistor between the VCC and DATA pins. Most breakout boards (blue PCB modules) already include this resistor, so you can skip it.
Always power the DHT22 from the 3.3V pin, not 5V, when using it with an ESP32 — ESP32 GPIO pins are not 5V tolerant, and while the data line itself is low-current, it's safest to keep the whole circuit at 3.3V logic levels.
Step-by-Step Instructions
- Wire the circuit exactly as shown in the table above. Double-check VCC and GND aren't reversed — this is the most common wiring mistake.
- Install the Arduino IDE if you haven't already, and add ESP32 board support via Boards Manager (search "esp32" and install the Espressif package).
- Install the required libraries: open Library Manager (Sketch > Include Library > Manage Libraries) and install "DHT sensor library" by Adafruit, along with "Adafruit Unified Sensor" (a dependency it requires).
- Select your board and port: Tools > Board > select your ESP32 board model, and Tools > Port > select the COM port it's connected to.
- Upload the code below.
- Open the Serial Monitor (Tools > Serial Monitor, or Ctrl+Shift+M) and set the baud rate to match the code (115200).
Complete Code
#include "DHT.h"
#define DHTPIN 4 // GPIO pin connected to DHT22 data line
#define DHTTYPE DHT22 // Change to DHT11 if using that sensor instead
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println("ESP32 DHT22 Temperature & Humidity Test");
dht.begin();
}
void loop() {
delay(2000); // DHT22 needs ~2 seconds between reads
float humidity = dht.readHumidity();
float tempC = dht.readTemperature(); // Celsius
float tempF = dht.readTemperature(true); // Fahrenheit
if (isnan(humidity) || isnan(tempC) || isnan(tempF)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" % | Temperature: ");
Serial.print(tempC);
Serial.print(" °C / ");
Serial.print(tempF);
Serial.println(" °F");
}
Explanation of Important Code Sections
-
#define DHTPIN 4— sets which GPIO pin the sensor's data line is connected to. Change this if you wire it to a different pin. -
DHT dht(DHTPIN, DHTTYPE);— creates the sensor object using the pin and sensor type defined above. -
dht.readHumidity()/dht.readTemperature()— these functions request a fresh reading from the sensor. PassingtruetoreadTemperature()returns Fahrenheit instead of Celsius. -
isnan()check — the DHT22 occasionally fails to return a valid reading, especially if read too frequently. This check prevents the program from printing garbage data when that happens. -
delay(2000)— the DHT22 can only be read reliably about once every 2 seconds; reading faster will cause failed readings.
Testing
After uploading, open the Serial Monitor. Within a few seconds you should see temperature and humidity values printing every 2 seconds.
Try breathing near the sensor (humidity should rise) or holding it gently (temperature should rise slightly) to confirm it's responding to real conditions.
Troubleshooting
"Failed to read from DHT sensor!" repeating constantly:
- Double-check wiring, especially that DATA is connected to GPIO 4 (or whatever pin your code specifies)
- Confirm the pull-up resistor is in place if using a bare sensor
- Try a different GPIO pin — some ESP32 pins are reserved or input-only and won't work for this
Readings show as nan:
-
Almost always a wiring issue or a
delay()that's too short between reads
Serial Monitor shows garbled text:
-
Baud rate mismatch — make sure the Serial Monitor's
baud rate matches
Serial.begin(115200)in the code
Board not detected / can't upload:
- Check you selected the correct board and port under Tools
- Try a different USB cable — some cables are power-only and don't carry data
Common Problems and Solutions
| Problem | Likely Cause | Solution |
|---|---|---|
| Constant NaN readings | Missing pull-up resistor | Add 10kΩ resistor between VCC and DATA |
| Inconsistent readings | Reading too frequently | Increase delay to 2000ms or more |
| No power to sensor | Wrong voltage pin used | Confirm 3.3V, not 5V or VIN |
Improvements / Upgrades
Once this basic version works, consider extending it:
- Display readings on an OLED or LCD screen instead of just Serial Monitor
- Turn the ESP32 into a web server so you can view readings from any browser on your network
- Log readings over time to an SD card or cloud service
- Add threshold-based automation (e.g., trigger a fan or alert if humidity exceeds a set value)
Frequently Asked Questions
Yes — just change DHTTYPE to
DHT11 in the code. Note that the DHT11
is less accurate and has a lower refresh rate than
the DHT22.
The DHT22's data line needs to be held at a steady "high" state between signal pulses. The pull-up resistor ensures reliable communication; without it, readings can be inconsistent or fail entirely.
For short runs (under a few meters), standard jumper wires work fine. For longer distances, use shielded cable and consider a slightly stronger pull-up resistor to maintain signal integrity.
The DHT22 is rated for roughly ±0.5°C temperature accuracy and ±2-5% humidity accuracy, which is sufficient for most hobbyist and home automation projects.
Conclusion
You now have a working ESP32 + DHT22 setup reading live temperature and humidity data.
This simple circuit is the foundation for a huge range of projects — weather stations, smart home sensors, greenhouse monitors, and more.
From here, the natural next step is turning this into a web-accessible dashboard, which we'll cover in an upcoming tutorial.
- Get link
- X
- Other Apps
Comments
Post a Comment