interface dht11 dht22 with esp32 and display values on web server




In this ESP32 web server tutorial, We will see how to display sensor values on the web server. Did you ever see a remote monitoring system where HMI based systems are used to monitor remote sensor values? Did you ever try to make a web server which can control or display values of different sensors on your local server? If yes. Then in this tutorial, you will correctly learn the example of interfacing DHT11, DHT21 and DHT22 interfacing with ESP32 and how to display its values on the Web server.  DHT11 and DHT22 sensors are used to measure temperature and humidity. We will measure these values with the help ESP32 development board and use ESP32 as a station mode to create a Web server. This Web server is used to monitor the values of temperature and humidity like this:interfacing DHT11 DHT22 with ESP32 and display values on web server




This web page will be used to display temperature value both in Celcius and Fahrenheit and humidity percentage.

Before starting this project, there are some necessary background concepts for understanding this project. These are the suggested readings.

Interfacing DHT11 , DHT22/ AM2302 to ESP32 – Wiring diagram

Connection diagrams for both are shown in pictures below. As you can see connections are straightforward.

Wiring diagram of DHT11 interfacing with ESP32
Wiring diagram of DHT11 interfacing with ESP32
Wiring diagram of DHT22 interfacing with ESP32
Wiring diagram of DHT22 interfacing with ESP32

Pinout of both DHT11 and DHT22 sensors are the same as you can see in the picture.

pinout DHT11 and DHT22

  • The first pin for both sensors is the Vcc pin. You should connect it with the 3.3volt pin of ESP32.
  • The second pin is data pin through we get data for temperature and humidity. Connect this terminal with GPIO4 of ESP32 and also connect data pin with a 10k pull-up resistor as shown in wiring diagrams.  Pull-up resistor is used to keep the data pin high for proper communication between microcontroller and sensor.  You can check the datasheet of DHT11 and DHT22 to get more information about it. DHT22 is also known with a name AM2302.
  • The third pin is not used. So we will not use it.
  • The fourth pin is a common ground terminal. Connect it with ground pin of ESP32 board.
  • You can place both sensor and board the on the breadboard and use some jumper wires to make connections.

installing DHT11 and DHT22 library in Arduino

Both DHT11 and DHT22 provides the output of temperature and humidity in the complex digital output format which can not be directly read with GPIO pins without writing any technique which can read these output signals. These sensors provide data through a single wire two-way communication protocol. A single process communication consists of 40 bits. But we do not need to worry about the working of these sensors and on which protocol we can receive this data. We have an Arduino library for DHT sensors which can be easily used to get values of temperature and humidity only by calling two lines of functions. We will see later on how to do it. Now let’s see how to install the DHT library in Arduino. This library is provided by Adafruit. Follow these steps to install the DHT sensor library:

  • Go to Sketch menu>> include file and click on manage libraries option.install DHT11 DHT22 library 1
  • When you click on manage libraries option, you will get this window. In this window write ‘DHT sensor‘ in the search bar and press enter. install DHT11 DHT22 library 2
  • You will see many options available for DHT11 and DHT22 libraries. Select Adafruit library and click on install button. You can select the latest version from the version window.install DHT11 DHT22 library 3
  • The same library can be used for both DHT11 and DHT22/AM2302 sensor.
  • After that, you will see the message of library correctly installed.
  • Now click on close button. This library is now successfully included in library manager of Arduino IDE.
  • This is a very powerful library. Because we can use the same library for different types of microcontrollers like Arduino and STM32 microcontrollers.

Adafruit also provides libraries for other sensors. So they provided a support package which is used to handle all sensor libraries. We also need to install the Adafruit Unified Sensor library. To install this, paste the  Adafruit Unified Sensor search bar and select this option and click on install button. Adafruit unified sensor library install

You may like to check other tutorials which used this sensor:

Create ESP32 Web server in station mode to display sensor values

So far you have learned about wiring diagram and how to install libraries for these sensors. Now let’s move to the more interesting part of this article. We will create an ESP32 Web server in station mode. This web server will serve the web pages to clients who try to access this web server through an existing network by using an IP address of ESP32. We will save the web page inside ESP32 and whenever any web client will make the request through HTTP for this web page through IP address, ESP32 web server will send these web pages to the client over HTTP protocol.

Now copy the code given below in Arduino IDE and upload this code to ESP32 board.  You need to make changes in code ssid and password name as shown below. In ssid, write the name of your WiFi network and in password write password of your WiFi.

ESP32 Web server reading sensor values enter password

Code for the ESP32 Web server

Now upload this code by clicking on the upload button.

#include <WiFi.h> 
#include <Wire.h>
#include "DHT.h"

// Uncomment one of the lines below for whatever DHT sensor type you're using!
//#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//DHT Sensor;
uint8_t DHTPin = 4; 
DHT dht(DHTPin, DHTTYPE); 
float Temperature;
float Humidity;

const char* ssid = "Enter SSID here"; 
const char* password = "Enter Password here";

WiFiServer server(80);

String header;

void setup() {
Serial.begin(115200);
pinMode(DHTPin, INPUT);
dht.begin();

Serial.print("Connecting to Wifi Network");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Successfully connected to WiFi.");
Serial.println("IP address of ESP32 is : ");
Serial.println(WiFi.localIP());
server.begin();
Serial.println("Server started");

}

void loop()
{
Temperature = dht.readTemperature(); 
Humidity = dht.readHumidity(); 
WiFiClient client = server.available();

if (client) 
{ 
Serial.println("Web Client connected ");
String request = client.readStringUntil('\r'); 
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
client.println("</style></head><body><h1>ESP32 Web Server Reading sensor values</h1>");
client.println("<h2>DHT11/DHT22</h2>");
client.println("<h2>Microcontrollerslab.com</h2>");
client.println("<table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>");
client.println("<tr><td>Temp. Celsius</td><td><span class=\"sensor\">");
client.println(dht.readTemperature());
client.println(" *C</span></td></tr>"); 
client.println("<tr><td>Temp. Fahrenheit</td><td><span class=\"sensor\">");
client.println(1.8 * dht.readTemperature() + 32);
client.println(" *F</span></td></tr>"); 
client.println("<tr><td>Humidity</td><td><span class=\"sensor\">");
client.println(dht.readHumidity());
client.println(" %</span></td></tr>"); 
client.println("</body></html>"); 
client.stop();
client.println();
Serial.println("Client disconnected.");
Serial.println("");
}
}

Getting the IP address

After uploading coding, open the serial monitor of Arduino IDE. you will see these messages on the serial monitor. DHT11 WEB SERVER ESP32

First, you will see the message ” Connecting to a WiFi network”. After ESP32 successfully connect to WiFi, you will see the successfully connect message and the IP address of ESP32. This IP address will be used by the web clients to access web pages over any web browser. Note down this IP address, we will need it to access the web server.

Accessing Web Server

Now open any web browser and enter the IP address which we noted in the last step. After you press enter, you will get this output in the web browser in table format. Its showing temperature in Celcius and Fahrenheit and also humidity in percentage. ESP32 Webserver reading sensor values without css

Code working

Now I will explain the working of sketch line by line. At the start of the sketch, we have added three libraries for WiFi driver, DHT sensors and wire library. These libraries are necessary to include to use its related functions within the code.

#include <WiFi.h>  // Include library for WiFi 
#include <Wire.h>  // Add library for Wire
#include "DHT.h"    //Add library for DHT11 and DHT11

This is used to define which type of DHT sensor we want to use. You can use this with DHT11, DHT21 and DHT22 sensor. You should uncomment the line according to the sensor you are using. For example, I have use DHT22 in this example, I have uncommented this and others are remain commented. DHTTYPE variable stores the name of the sensor we are using.

// Uncomment the line according to your selection of sensing device
//#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321

We have defined a name of GPIO pin with which we will connect the DHT11/DHT22 sensor. We are using GPIO pin number four. Therefore we have to define pin number four.

uint8_t DHTPin = 4;

This line will create the object of DHT according to our define pin number and DHT type. We have defined both these parameters in the last steps.

DHT dht(DHTPin, DHTTYPE);

These two float type variable will be used to store values of temperature and humidity.

float Temperature;
float Humidity;

These variable stores the name and password of the WiFi network.

const char* ssid = "Enter the name of your network"; 
const char* password = "Enter the password here";

This line will create the instance of web server library over port number 80.  For the HTTP protocol, 80 is a default port number. So we will be using this default port number. The advantage of using this default port number is that we will not need to specify port number while accessing web server through an IP address.

WiFiServer server(80);
String header;   //Variable used to store requests from web clients

Inside setup function

Now inside this function, the first line will initialize the serial communication with the baud rate of 115200 and pinMode function will make the GPIO pin four as a digital input pin. The dht.begin() function starts to read the values of DHT11/DHT22 sensor.

Serial.begin(115200);
pinMode(DHTPin, INPUT);
dht.begin();

Now, this part of the sketch will try to connect with a WiFi network and after successfully connecting with the network, it will display the message and IP address of the ESP32 board.

Serial.print("Connecting to Wifi Network");   // Display this string on serial monitor 
Serial.println(ssid);    // Print name of ssid on the serial monitor
WiFi.begin(ssid, password);   // It will start connecting to the network
while (WiFi.status() != WL_CONNECTED)    // This condiction checks either connected to 
{                                                                  // to a network or not
delay(500);                                                // it will keep try after every half second
Serial.print(".");                                         // It will exist this loop upon connection
}
Serial.println("");
Serial.println("Successfully connected to WiFi.");    // Display this message on Serial monitor
Serial.println("IP address of ESP32 is : ");
Serial.println(WiFi.localIP());   // This function will display IP address of ESP32 or station mode ESP32
server.begin();                      // This statement will start the server. Now web client can connect to ESP32 web server
Serial.println("Server started"

Inside the loop function

These lines get the values of temperature and humidity and save them in these two variables.

Temperature = dht.readTemperature(); 
Humidity = dht.readHumidity();

This server.available function checks if any web client is available or not. If it is available logical high value will be stored inside this client variable.

WiFiClient client = server.available();

if the value of the client variable is logical high this ‘if’ condition becomes true.  Inside this ‘if” condition we are displaying web page and values of sensor data on the web page. Every HTTP request from a web client end with ‘\r’, so this client.readStringUntil() function listens to the request of web client until \r is not found.

if (client) 
{ 
Serial.println("Web Client connected ");
String request = client.readStringUntil('\r');

After that we client.println() function sends HTML files to web page. So to understand this part, lets me understand some basics of this HTML and how to make tables in HTML because we are displaying data in table format.

To create a table in HTML, we use <table> and </table> tags.

  • As you know every table consists of rows and columns. So <tr> and </tr> tags are used to add row to a table.
  • Every table also has a heading. To add heading to a table we use <th> and </th>  tags.
  • To define the number of columns or cells in each row, we use these <td> and </td> tags.

In this example, we measure three values. Therefore we will need three rows and two cells and one heading with measurement and value message.

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="data:,">
  
</head>
<body>

  <table>
    <tr>
      <th>MEASUREMENT</th>
      <th>VALUE</th>
    </tr>
    <tr>
      <td>Temperature in Celsius</td>
      <td>--- *C</td></tr>
    <tr>
      <td>Temperature in Fahrenheit</td>
      <td>--- *F</td>
    </tr>
    <tr>
      <td>Humidity</td>
      <td>--- %</td>
    </tr>
</body>
</html>

So this code will create a table which will look like this:

Table HTML web server ESP32 sensor values on web page

So this code first creates heading with the message of ‘measurement’ in one cell and the message of ‘value’ in another cell. After that, we created three rows to display values of temperature and humidity. Now lets come to Arduino programming part of this project of displaying sensor values on the Web server using ESP32.

After web client requests for a web page, ESP32 web server responds to the web client with an HTML file which will show as a web page in web browser. The client.println() function is used to send the HTML files to web client.  This code will send the HTML files to the web client along with values of temperature and humidity in tabular form.

client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
client.println("</style></head><body><h1>ESP32 Web Server Reading sensor values</h1>");
client.println("<h2>DHT11/DHT22</h2>");
client.println("<h2>Microcontrollerslab.com</h2>");
client.println("<table><tr><th>MEASUREMENT</th><th>VALUE</th></tr>");
client.println("<tr><td>Temp. Celsius</td><td><span class=\"sensor\">");
client.println(dht.readTemperature());
client.println(" *C</span></td></tr>"); 
client.println("<tr><td>Temp. Fahrenheit</td><td><span class=\"sensor\">");
client.println(1.8 * dht.readTemperature() + 32);
client.println(" *F</span></td></tr>"); 
client.println("<tr><td>Humidity</td><td><span class=\"sensor\">");
client.println(dht.readHumidity());
client.println(" %</span></td></tr>"); 
client.println("</body></html>");

To send the value of temperature, you will send this value through dht.readtemperature() function as shown below. First, it will send a new table row entry and send the value between these tags.

client.println("<tr><td>Temp. Celsius</td><td><span class=\"sensor\">");
client.println(dht.readTemperature());
client.println(" *C</span></td></tr>");

This line will stop the web client connection.

client.stop();

Adding styles to a web page to look more professional

As you see the table which displaying values is not looking attractive without colors and table borders. So now let’s add some CSS to this code and make to more professionally looking good like shown below. Esp32 web server DHT11 DHT22 values on web page with css

Add this code inside the HTML part before the closing heading tag </head>. you will see the web page like shown above. Check this picture to know where you need to add this code which will add style to the web page.

web page CSS additon ESP32 web server sensor values

client.println("<style>body { text-align: center; font-family: \"Arial\", Arial;}");
client.println("table { border-collapse: collapse; width:40%; margin-left:auto; margin-right:auto;border-spacing: 2px;background-color: white;border: 4px solid green; }");
client.println("th { padding: 20px; background-color: #008000; color: white; }");
client.println("tr { border: 5px solid green; padding: 2px; }");
client.println("tr:hover { background-color:yellow; }");
client.println("td { border:4px; padding: 12px; }");
client.println(".sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }");

CSS stands for Cascading Style Sheets and it is used for adding colors and styles to web pages.  In the above code, CSS adds style and colors to each element of the table like rows, cells, and heading.  you can check more information about creating CSS and HTML here. ESP32 Web server reading sensor values with css

This is how we can interface dht11/dht22 with esp32 and display values on the web server.

you may also like to check other ESP32 projects :



Leave a Comment