Phase 6 11 min read read

DHT11/DHT22 with ESP32

DHT11/DHT22 with ESP32 DHT11/DHT22 with ESP32 — Manuscript, Part 1 SEO title DHT11/DHT22 with ESP32 – Complete Temperature and Humidity Guide Meta description Learn how to connect DHT11…

Updated June 19, 2026

DHT11/DHT22 with ESP32

DHT11/DHT22 with ESP32 — Manuscript, Part 1

SEO title

DHT11/DHT22 with ESP32 – Complete Temperature and Humidity Guide

Meta description

Learn how to connect DHT11 and DHT22 sensors to ESP32. Compare accuracy, wiring, timing, error handling, OLED dashboards, data logging, troubleshooting, and real-world uses.

1. Introduction

DHT11 and DHT22 are widely used temperature-and-humidity sensors for ESP32 projects because they are inexpensive, easy to wire, and supported by common Arduino libraries. They are useful for basic room monitoring, greenhouse prototypes, appliance status displays, and simple connected dashboards.

Their convenience has limits. They use a timing-sensitive single-wire protocol, update slowly, and need careful error handling. A successful first reading does not prove a design is reliable. Good projects respect the sensor’s minimum sampling interval, validate failed reads, avoid heating the sensor with nearby electronics, and show a meaningful fault state rather than silently using old or invalid data.

This guide explains both sensors from first principles and helps readers choose between DHT11, DHT22, and the existing BME280 path. Before starting, complete the ESP32 Pinout Guide and BME280 with ESP32 guide. The ESP32 I2C Tutorial remains useful for the OLED and data-logging peripherals that often accompany a DHT sensor, even though DHT itself is not I2C.

2. What Are DHT11 and DHT22?

DHT11 and DHT22 are combined temperature-and-humidity sensors. They contain a humidity-sensing element, a temperature sensor, a small controller, factory calibration information, and a digital output stage. The host ESP32 requests a reading, then receives a short data packet containing humidity, temperature, and a checksum.

DHT11 is the lower-cost, lower-resolution option. DHT22, also sold as AM2302 in some forms, has a broader measurement range and generally better precision. Both are suited to learning and non-critical environmental monitoring. Neither should be treated as laboratory instrumentation or as the sole control input for safety-critical heating, cooling, medical, or industrial systems.

3. DHT11 vs DHT22

Feature DHT11 DHT22

Typical temperature range 0 to 50 °C About -40 to 80 °C

Typical humidity range 20 to 80% RH 0 to 100% RH

Temperature resolution 1 °C 0.1 °C

Humidity resolution 1% RH 0.1% RH

Sampling interval About 1 second About 2 seconds

Best fit Basic demonstrations Better hobby environmental monitoring

Choose DHT11 when cost and simple demonstration are the priorities. Choose DHT22 when wider range and finer readings matter. If atmospheric pressure, I2C integration, and a richer environmental profile are needed, choose BME280 instead.

4. DHT22 vs BME280

Capability DHT22 BME280

Temperature Yes Yes

Humidity Yes Yes

Pressure No Yes

Interface Timing-sensitive digital data line I2C or SPI

Multiple devices Requires separate data pins Can share I2C bus by address

Typical project role Simple temperature/humidity node Environmental dashboard or weather system

DHT22 is not inferior in every situation. It has a straightforward wiring model and is often easy to understand for a first sensor project. BME280 is usually the stronger fit for expandable systems, especially where an OLED, RTC, or other I2C devices already share the same bus.

5. Sensor Specifications

The sensor package matters as much as its name. A bare DHT11 or DHT22 sensor may need an external pull-up resistor on its data line. A breakout module often includes that resistor already. Check the board before adding another one.

Property DHT11 DHT22

Supply Usually 3.3–5 V module dependent Usually 3.3–5 V module dependent

Data protocol Proprietary single-wire timing Proprietary single-wire timing

ESP32 logic Use 3.3 V GPIO Use 3.3 V GPIO

Read interval Do not poll excessively Wait at least about two seconds

Use a stable supply and common ground. A long, noisy wire or an overloaded breadboard power rail can create checksum failures that resemble software bugs.

6. Wiring DHT11 to ESP32

Use a safe general-purpose GPIO such as GPIO4 for the sensor data line.

DHT11 pin/module pin ESP32 connection Purpose

VCC 3V3 Power

GND GND Shared reference

DATA GPIO4 Digital sensor data

If you have a bare sensor rather than a module, add an appropriate pull-up resistor between VCC and DATA, commonly around 4.7 kΩ to 10 kΩ depending on the design and wiring length.

7. Wiring DHT22 to ESP32

DHT22 wiring is similar:

DHT22 pin/module pin ESP32 connection Purpose

VCC 3V3 Power

GND GND Shared reference

DATA GPIO4 Digital sensor data

Keep the sensor away from the ESP32 regulator, OLED power circuitry, and Wi-Fi antenna region when measuring room air. The temperature you want is the air temperature around the monitored environment, not the heat generated by the controller.

8. Required Libraries

Install the following libraries through Arduino IDE Library Manager:

DHT sensor library by Adafruit

Adafruit Unified Sensor

The DHT library handles protocol timing and checksum validation. The Unified Sensor dependency gives a common structure used across sensor libraries.

9. Reading Temperature

#include <DHT.h>

#define DHTPIN 4

#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

void setup() {

Serial.begin(115200);

dht.begin();

}

void loop() {

float temperature = dht.readTemperature();

if (isnan(temperature)) {

Serial.println("Temperature read failed");

} else {

Serial.printf("Temperature: %.1f Cn", temperature);

}

delay(2000);

}

Explanation: the ESP32 initializes a DHT22 on GPIO4, reads Celsius temperature, and rejects invalid readings.

Expected output:

Temperature: 24.7 C

Troubleshooting: verify that DHTTYPE matches the physical sensor. Using DHT11 for a DHT22, or the reverse, produces failed or implausible values. Do not poll a DHT22 faster than its required interval.

10. Reading Humidity

float humidity = dht.readHumidity();

if (isnan(humidity)) {

Serial.println("Humidity read failed");

} else {

Serial.printf("Humidity: %.1f %%n", humidity);

}

Explanation: humidity is returned as relative humidity in percent.

Expected output:

Humidity: 54.2 %

Troubleshooting: invalid readings can result from timing violations, loose wiring, an incorrect sensor type, condensation, or supply instability. Do not treat a failed reading as zero humidity.

11. Error Handling

A robust sensor loop never assumes every read is valid. Keep the last known good value, note the time of the last successful update, and make failure visible in Serial output, an OLED, or a connected dashboard. A greenhouse controller should show “sensor unavailable” rather than pretend the air is at 0 °C and 0% humidity.

12. Sensor Timing Considerations

DHT sensors do not behave like a fast analog input. The ESP32 begins a transaction, the sensor responds with precisely timed pulses, and the library interprets those pulses as bits. Wi-Fi tasks, interrupts, poor wiring, or rapid repeated reads can interfere with that process.

Use a DHT11 interval of roughly one second or longer. Use a DHT22 interval of roughly two seconds or longer. Reading more often does not create fresher environmental data; it usually creates failed reads or repeated values.

In larger projects, use a timestamp-based schedule rather than long blocking delays:

unsigned long lastRead = 0;

const unsigned long interval = 2000;

void loop() {

if (millis() – lastRead >= interval) {

lastRead = millis();

float t = dht.readTemperature();

float h = dht.readHumidity();

if (!isnan(t) && !isnan(h)) {

Serial.printf("%.1f C, %.1f %%n", t, h);

}

}

// Wi-Fi, display, and control tasks continue here.

}

Explanation: the sensor is read on a controlled interval while the rest of the application remains responsive.

Expected output: a valid temperature/humidity line approximately every two seconds.

Troubleshooting: if values fail only after Wi-Fi is enabled, reduce unnecessary blocking work, verify the sensor interval, and inspect power stability.

13. Accuracy and Calibration

DHT sensors are appropriate for trend monitoring and basic environmental awareness. They should not be treated as certified reference instruments. Their accuracy is affected by placement, airflow, heat from nearby electronics, direct sunlight, moisture, and response time.

Calibration is usually practical rather than mathematical. Compare readings over time against a trusted reference in the same location. If the DHT is consistently warmer because it sits near the ESP32 regulator, improve placement before applying a software offset. A software correction can hide a design problem and may fail when ambient conditions change.

Do not place the sensor inside a sealed plastic enclosure unless the enclosure itself is the environment being measured. For room monitoring, expose the sensor to representative air while protecting it from direct splashes, dust, and physical damage.

14. OLED Integration

The DHT sensor uses GPIO4 in this example, while the SSD1306 OLED uses I2C on GPIO21 and GPIO22. They can operate together because they use different interfaces.

#include <Wire.h>

#include <DHT.h>

#include <Adafruit_GFX.h>

#include <Adafruit_SSD1306.h>

#define DHTPIN 4

#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

Adafruit_SSD1306 display(128, 64, &Wire, -1);

void setup() {

dht.begin();

Wire.begin(21, 22);

if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {

while (true) delay(10);

}

}

void loop() {

float t = dht.readTemperature();

float h = dht.readHumidity();

display.clearDisplay();

display.setTextColor(SSD1306_WHITE);

display.setTextSize(1);

display.setCursor(0, 0);

display.println("ROOM CLIMATE");

if (isnan(t) || isnan(h)) {

display.setCursor(0, 24);

display.println("DHT sensor error");

} else {

display.setCursor(0, 18);

display.printf("Temp: %.1f C", t);

display.setCursor(0, 34);

display.printf("Hum : %.1f %%", h);

}

display.display();

delay(2000);

}

Explanation: the display renders either valid measurements or an explicit sensor fault.

Expected output: a small room-climate dashboard or “DHT sensor error.”

Troubleshooting: if the OLED works but DHT fails, troubleshoot the DHT data pin and timing separately. If the DHT works in Serial Monitor but the display is blank, verify the OLED address and I2C wiring.

15. Data Logging

Data logging turns isolated measurements into useful trends. A simple first step is Serial output captured by a computer. A more complete design can write data to an SD card, send it to an MQTT broker, or post it to a web endpoint.

Log a timestamp, temperature, humidity, sensor status, and optional device state. Avoid logging every loop iteration. For indoor monitoring, one reading every minute may be more useful than thousands of nearly identical samples.

A useful record resembles:

2026-06-19T12:00:00Z,24.7,54.2,OK

If a read fails, log the failure explicitly instead of carrying a bad value forward without explanation.

16. Real-World Applications

The [ESP32 Weather Station](/projects/esp32-iot-weather-station/) can use DHT22 as a simple temperature/humidity source. The [ESP32 Smart Irrigation System](/projects/esp32-smart-irrigation-system/) can use ambient humidity as contextual information alongside soil moisture. The [ESP32 Air Quality Monitor](/projects/esp32-air-quality-monitor/) can display temperature and humidity to help users interpret indoor conditions.

DHT values should inform monitoring and user feedback. They should not be the only basis for safety-critical HVAC, agricultural, or health decisions.

17. Common Problems

Symptom Likely cause First action

nan values Wrong sensor type, timing, wiring Check library type and data pin

Reads work once then fail Polling too quickly Enforce the minimum interval

Temperature is too high ESP32 heat or poor placement Move sensor away from heat

Humidity is unstable Airflow, condensation, loose wiring Check placement and connections

Values are always zero Wrong pin or sensor failure Test with a minimal sketch

OLED works but sensor does not Separate-interface issue Debug DHT GPIO independently

18. Troubleshooting

Work from physical causes to software causes:

Verify VCC, GND, and DATA wiring.

Confirm the correct GPIO is defined.

Confirm DHT11 or DHT22 matches the hardware.

Test a minimal Serial-only sketch.

Wait long enough between reads.

Check supply voltage and common ground.

Move the sensor away from heat sources.

Add or verify the pull-up resistor if using a bare sensor.

Do not introduce Wi-Fi, OLED code, cloud logging, and relay control until the basic sensor sketch is stable.

19. Best Practices

Read DHT11 no more often than about once per second.

Read DHT22 no more often than about once per two seconds.

Validate every reading.

Keep last-known-good values separate from current failures.

Use 3.3 V ESP32 logic.

Keep data wiring short and tidy.

Avoid direct sun, water, and controller heat.

Display units clearly.

Log sensor faults.

Choose BME280 instead when pressure and I2C expansion are important.

20. Conclusion

DHT11 and DHT22 make environmental sensing approachable, but dependable use depends on timing, wiring, validation, and honest treatment of measurement limits. DHT11 is suitable for basic demonstrations. DHT22 offers a stronger hobby-grade range and resolution. BME280 is often the better long-term choice when pressure, I2C, and multi-device expansion matter.

FAQ

What is the difference between DHT11 and DHT22?

DHT22 has broader ranges and finer resolution; DHT11 is simpler and lower cost.

Can DHT11 run on ESP32?

Yes, with a suitable GPIO data pin, common ground, and correct library configuration.

Can DHT22 use 3.3 V?

Most breakout modules support 3.3 V operation; verify the specific board documentation.

Why does DHT return nan?

Usually incorrect sensor type, wiring, polling too quickly, timing interference, or power issues.

How often should DHT22 be read?

About every two seconds or slower.

Does DHT need a pull-up resistor?

Bare sensors commonly do; breakout modules may already include one.

Is DHT22 better than BME280?

Not universally. BME280 adds pressure and I2C support; DHT22 can be simpler for basic monitoring.

Can DHT11 and DHT22 share one GPIO?

No. Each sensor needs its own data line unless a specific supported architecture is used.

Can I display DHT readings on OLED?

Yes. The DHT uses a GPIO line while the OLED normally uses I2C.

Is DHT suitable for outdoor weather stations?

It can be used in protected, ventilated housings, but exposure, condensation, and accuracy expectations must be managed.

Internal linking plan

Prerequisite links:

ESP32 I2C Tutorial

ESP32 Pinout Guide

BME280 with ESP32

Related existing projects:

ESP32 Weather Station

ESP32 Smart Irrigation System

ESP32 Air Quality Monitor

Related project mapping

Project DHT role

Weather Station Basic local temperature and humidity measurement

Smart Irrigation System Ambient humidity context beside soil moisture

Air Quality Monitor Comfort and environmental context for indoor readings

Originality review

This draft is newly written for ESP32Engine. It does not reuse project text, unpublished batch content, or existing guide prose.

Projects to Build

Put this knowledge to work — try one of these hands-on projects.