Read temperature and humidity with the DHT11

Connect the DHT11 sensor module to the ESP32 and print the room temperature and humidity every two seconds.
  • Level:Beginner
  • Duration: 40 min
  • Ages 12+
  • Platform: ESP32

What you'll need

Read temperature and humidity with the DHT11 – EEMENTOR STEM lesson

The DHT11 measures both temperature and humidity and sends the result over a single data wire. It's the heart of weather stations, greenhouse monitors and smart thermostats.

What you'll learn

  • How to install a library with the Library Manager
  • How to read a digital sensor
  • How to handle a failed reading

What you need

  • ESP32-DevKitC V4 board and USB cable
  • DHT11 temperature and humidity module (KY-015)
  • Breadboard
  • 3 jumper wires

Step 1: Install the library

Open Tools → Manage Libraries, search for DHT sensor library and install the one by Adafruit. When asked, also install its dependency, Adafruit Unified Sensor.

Step 2: Wiring

The module has three pins. Check the labels printed on your module: usually S (signal), the middle pin (power) and - (ground).

Breadboard wiring diagram: Read temperature and humidity with the DHT11
Breadboard view. Check each connection against the wiring table below.
DHT11 module pin ESP32 pin
S (signal) GPIO 27
Middle (+) 3V3
- (ground) GND

Step 3: The sketch

#include <DHT.h>

const int DHT_PIN = 27;
DHT dht(DHT_PIN, DHT11);

void setup() {
  Serial.begin(115200);
  dht.begin();
}

void loop() {
  delay(2000); // the DHT11 needs about 2 seconds between readings

  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature(); // Celsius

  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Couldn't read the sensor, check the wiring");
    return;
  }

  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.print(" °C   Humidity: ");
  Serial.print(humidity);
  Serial.println(" %");
}

How it works

The library asks the sensor for a reading, and the sensor answers with a short burst of pulses on the data wire. If something goes wrong, the library returns NaN ("not a number"), which the sketch checks with isnan(). The DHT11 is accurate to about ±2 °C and ±5 % humidity, which is fine for a room monitor.

Try this next

  • Breathe gently on the sensor and watch the humidity rise.
  • Add the LED from lesson 1 and switch it on when the temperature goes above 26 °C.

Troubleshooting

  • "Couldn't read the sensor": check that S is on GPIO 27 and the power pins aren't swapped.
  • Compile error about DHT.h: the library isn't installed. Repeat step 1.

Build it yourself

Everything used in this lesson comes in one kit, with parts tested by our engineers.

ESP32 IoT Starter Kit | Arduino IDE Compatible | Free Tutorials $49.00

Shop the kit