ESP32 Sensor: DHT11 Temperature and Humidity Sensor
DHT11 Temperature and Humidity Sensor
DHT11 can measure both temperature and humidity, it is a popular, cost-effective sensor. In this article we will discuss how to read temperature and humidity with ESP32 and DHT11.
Hardware Required
- ESP32 development board
- DHT11 temperature and humidity sensor
- Jumper wires
Wire Connection
- Connect V of DHT11 to the 3.3V or 5V pin on the ESP32.
- Connect G of DHT11 to one of the GND pins on the ESP32.
- Connect S pin of DHT11 to a GPIO pin on the ESP32 (e.g., GPIO 5).
The supply voltage for the DHT11 is 3~5.5V.
Installing the DHT Library
We will use the DHT library to read temperature and humidity from the DHT11 sensor.
Search for DHT library in the PlatformIO Library Manager and install it.
Library installation, click on the "Add to Project" button.
Then choose the project we defined earlier and click on the "Add" button.
Code
Here is the example code to read temperature and humidity from the DHT11 sensor and print it to the serial monitor.
#include <Arduino.h>
#include "DHT.h"
#define DHTPIN 5 // GPIO pin the sensor is connected to
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
dht.begin();
}
void loop() {
// Reading temperature and humidity
float h = dht.readHumidity();
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print the results to the serial monitor
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("% Temperature: ");
Serial.print(t);
Serial.println("°C ");
delay(2000); // Delay between measurements
}
Upload the code to the ESP32 and then open the serial monitor.
We can see the temperature and humidity readings, shows as below:
The project upload to github, link: ESP32-Tutorials/01_DHT11 at main · ESP32Cubes/ESP32-Tutorials (github.com)