ESP32: DHT22 Temperature & Humidity
FREE SIMULATOR EXAMPLE · BEGINNER
ESP32: DHT22 Temperature & Humidity
This example reads temperature and humidity from a DHT22 sensor wired to GPIO4 of the ESP32 and prints both values to the Serial Monitor every two seconds. It uses Adafruit’s DHT sensor library — the same one you would install on real hardware — so what you learn here transfers directly.
| Board | ESP32 DevKit (Xtensa LX6, 240 MHz) |
|---|---|
| Difficulty | beginner |
| Category | sensors |
| Libraries | DHT sensor library, Adafruit Unified Sensor |
| Runs in | Sensbench browser simulator — free, no account |

The exact circuit you get when you open this example — already wired, ready to run.
The sketch
// ESP32 — DHT22 Temperature & Humidity Sensor
// Requires: Adafruit DHT sensor library
// Wiring: DATA → GPIO4 | VCC → 3V3 | GND → GND
#include <DHT.h>
#define DHT_PIN 4 // GPIO 4
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);
void setup() {
Serial.begin(115200);
dht.begin();
delay(2000);
Serial.println("ESP32 DHT22 ready!");
}
void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("DHT22: waiting for sensor...");
return;
}
Serial.printf("Temp: %.1f C Humidity: %.1f %%\n", t, h);
}
How it works
The DHT22 talks a single-wire protocol: one data line, strict timing, 40 bits per reading. You never see any of that — the DHT object from the library handles the bit-banging. dht.begin() in setup(), then dht.readTemperature() and dht.readHumidity() in the loop.
Notice the isnan() check. DHT sensors fail checksums regularly — it is normal, not a bug in your code. The library returns NaN when a read goes bad, and the sketch just waits for the next cycle instead of printing garbage.
Wiring is three wires: DATA to GPIO4, VCC to 3V3, GND to GND. The simulator adds the sensor to the canvas with those connections pre-made.
Before you build it for real
On a real build, the DATA line wants a 10 kΩ pull-up to 3V3 — most DHT22 breakout modules include one, a bare sensor does not. If readings are all NaN on real hardware, that is the first thing to check. Second: the DHT22 is slow. It needs about 2 seconds between reads, which is why the sketch has delay(2000) — poll faster and you get stale or NaN values. And power it from 3V3, not 5 V, so the data line matches the ESP32’s logic level.
Get the parts
Related examples
FAQ
Why does the Serial Monitor say "waiting for sensor"?
That branch fires when the library reads NaN — a failed checksum or a timing hiccup. Occasional NaNs are normal for DHT sensors. In the simulator it usually means the sensor was just added; on hardware, check the pull-up resistor and wiring.
Can I use a DHT11 instead?
Yes. Change DHT_TYPE to DHT11 and the rest of the sketch is identical. The DHT11 is cheaper, less accurate, and has no decimal resolution — fine for a demo, annoying for a thermostat.