Measuring Temperature, humidity is become an important task in lives. As we monitor temperatures in various places for example a freezer or a cake shop. The Cake shop needs to maintain a low temperature else the icing on the cakes will substantially melt. In this project, we will build a system that will monitor the temperature and humidity with the ESP32 and will be able to monitor the same using a local webpage.
The ESP32 has an inbuilt temperature sensor, but it fails miserably considering that the ESP32 dissipates its own heat. In such cases we cannot accurately measure the temperature.
Few things you might need to know before we get going:
- Installation of the Arduino IDE for the ESP32
- Configuration of the ESP32
- How to create a Web Server using ESP32
- Basic HTML knowledge is recommended
In this tutorial you will learn how to measure the temperature and humidity. The DHT sensors have an on-board chip that converts the analog temperature to digital form. The DHT sensors are almost compatible to use with any microcontroller. We will be using the DHT11 in our project. (You can use any model of the DHT, but make sure the conversions in the code are done correctly.)
Components Required
- ESP32 x 1
- DHT11 x 1
- 220Ω Resistor x 1
- Breadboard
- Jumper Cables
How does the DHT11 or Humidity Sensor Work?
The humidity sensing component of the DHT11 is a moisture holding substrate with the electrodes applied to the surface. When water vapor is absorbed by the substrate, ions are released by the substrate which increases the conductivity between the electrodes. The change in resistance between the two electrodes is proportional to the relative humidity. Higher relative humidity decreases the resistance between the electrodes while lower relative humidity increases the resistance between the electrodes.
DHT11 – Pin Diagram
- Vcc pin supplies power for the sensor. Connected to 3.3V on the ESP32.
- Data pin is used to communicate between the ESP32 and the sensor
- NC is Not Connected
- GND is the ground pin. Common grounded with the ESP32.
How does the DHT11 work with the ESP32?
The DHT11 converts the resistance measurement to relative humidity on an chip mounted to the back of the unit and transmits the humidity and temperature readings directly to the any GPIO4 pin on the ESP32.
Circuit Diagram
Working Principle
The GPIO4 will be programmed to read the signal from the DHT11 and then the code will perform the voltage level conversion to temperature and humidity readings.
After connecting the circuit we will have to add the DHT Adafruit Sensor library. Then we can upload the code and get the readings from the DHT.
The ESP32 will start a web server and the webpage will display the current Temperature and Humidity in the vicinity of the DHT sensor.
Code Simplified
Add the DHT and Adafruit Sensor Library so that will allow us to read the signal from the DHT sensor.
Download all the below libraries
Download all the above libraries and add them to your library folder.
In your Arduino IDE, you can go to Sketch > Include Library > Add .zip Library and select the libraries you’ve just downloaded.
Before you run the code make sure that the WiFi SSID or name is changed along with the password in the code. Once you do the changes you can upload the code and perform the activity.
After uploading the code, the ESP32 will connect to your local network. If you press reset it will try to reconnect again. So in some cases when the ESP32 is already connected make sure you press reset and then enable on the ESP32.
#include "WiFi.h" //adding the wifi libary
#include "ESPAsyncWebServer.h" //Async basically allows multiple requests on the webserver
#include <Adafruit_Sensor.h> // To read all the values from the DHT sensor (conversions are offered by adafruit sensors)
#include <DHT.h> //DHT library that has all the functions of the Sensor
const char* ssid = "_____"; //add your wifi name here
const char* password = "_____"; //add your wifi password here
#define DHTPIN 4 // GPIO pin that is connected to the DHT 4
#define DHTTYPE DHT11 // DHT 11 (you could change it to the type of DHT you have. But make sure the library includes the DHT type)
DHT dht(DHTPIN, DHTTYPE);
AsyncWebServer server(80); // Create AsyncWebServer object on port 80 (80 is default)
String readDHTTemperature() {
float t = dht.readTemperature(); //reading temp in degree centigrades 'C
// Check for a reading else try again.
if (isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return "--";
}
// if reading is found then display the value
else {
Serial.println(t);
return String(t);
}
}
String readDHTHumidity() {
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
if (isnan(h)) {
Serial.println("Failed to read from DHT sensor!");
return "**";
}
else {
Serial.println(h);
return String(h);
}
}
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<script src="https://kit.fontawesome.com/e10a7f45ba.js" crossorigin="anonymous"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<style>
html {
font-family: Arial;
display: inline-block;
margin: 0px auto;
text-align: center;
}
h2 { font-size: 3.0rem; color:#2d81c8; }
p { font-size: 3.0rem; }
.units { font-size: 1.2rem; }
.dht-labels{font-size: 1.5rem; vertical-align:middle;padding-bottom: 15px;}
.temp_number{color:#2d81c8;}
.hum_number{color:#2d81c8;}
</style>
</head>
<body>
<h2>DHT Server - Simplified</h2>
<p>
<i class="fa-solid fa-temperature-quarter"></i>
<span class="dht-labels">Temperature</span>
<span class="temp_number" id="temperature">%TEMPERATURE%</span>
<sup class="units">°C</sup>
</p>
<p>
<i class="fa-solid fa-percent"></i>
<span class="dht-labels">Humidity</span>
<span class="hum_number" id="humidity">%HUMIDITY%</span>
<sup class="units">%</sup>
</p>
</body>
<script>
setInterval(function ( ) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("temperature").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/temperature", true);
xhttp.send();
}, 10000 ) ;
setInterval(function ( ) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("humidity").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/humidity", true);
xhttp.send();
}, 10000 ) ;
</script>
</html>)rawliteral";
// Replaces placeholder with DHT values
String processor(const String& var){
//Serial.println(var);
if(var == "TEMPERATURE"){
return readDHTTemperature();
}
else if(var == "HUMIDITY"){
return readDHTHumidity();
}
return String();
}
void setup(){
// Serial port for debugging purposes
Serial.begin(115200);
dht.begin();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", readDHTTemperature().c_str());
});
server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", readDHTHumidity().c_str());
});
// Start server
server.begin();
}
void loop(){
}
Now you can run the serial monitor on your computer and you will find out the Local IP of your ESP32. Connect to it via a web browser from any device that is connected to the same network.
Web Page Layout
Customize the layout as per your requirements. The most basic HTML code is used in the above webpage. The webpage only displays the temperatures that are read from the DHT11 sensor and fetches the icons from an online site. We will need to add javaScript so that we have a functions that keeps on making the request to the ESP32 about the currents humidity and temperature, setting up the intervals and also displaying the values on the webpage.
The ESP32 will get connected to the WiFi and display an IP address. For example : Open the IP address on to your web browser 192.168.100.19
Conclusion
Now you can measure the temperature and humidity using the DHT11 on the web browser. You can use any DHT sensor to perform this activity.