Have you ever wished you could use your mobile, tablet, or PC to monitor the temperature and humidity in your home, walk-in cooler, or wine cellar at any time? Then this IoT project could be a great place to start!

This project employs the ESP32 as the control device, which connects to an existing WiFi network and creates a Web Server. When a device connects to this web server, the ESP32 will read the temperature and relative humidity from the DHT11/DHT22 sensor and send it to the device�s web browser with a nice interface. Excited? Let�s get started!

There are a few concepts you should be familiar with before continuing with this tutorial. If any of the tutorials below are unfamiliar to you, consider reading through them first:

The ESP32 has a built-in temperature sensor, so why not use that?

The ESP32 does, in fact, include a temperature sensor with a temperature range of -40�C to 125�C. This temperature sensor produces a voltage proportional to temperature, which is then converted to digital form by an internal analog-to-digital converter.

According to the ESP32 datasheet, the issue with this temperature sensor is that the offset varies from chip to chip due to process variation. Temperature measurements are also affected by the heat generated by the Wi-Fi circuitry. As a result, the internal temperature sensor is only appropriate for applications that detect temperature changes rather than absolute temperatures.

Wiring a DHT11/DHT22 sensor to an ESP32

Connecting a DHT11/DHT22 sensor to an ESP32 is pretty easy. Begin by placing the ESP32 on your breadboard, making sure that each side of the board is on a different side of the breadboard.

Place the sensor on your breadboard next to the ESP32. Connect the sensor�s VCC pin to the ESP32�s 3.3V pin and ground to ground. Connect the sensor�s Data pin to the ESP32�s D4 pin. Finally, add a 10K? pull-up resistor between VCC and the data line to keep it HIGH for proper communication between the sensor and the ESP32.

The image below shows the wiring.

Wiring Fritzing Connecting DHT22 Temperature Humidity Sensor with ESP32
Wiring DHT22 Temperature Humidity Sensor with ESP32
Wiring Fritzing Connecting DHT11 Temperature Humidity Sensor with ESP32
Wiring DHT11 Temperature Humidity Sensor with ESP32

Installing DHT Sensor Library

To begin reading sensor data, you will need to install the DHT sensor library. It is available from the Arduino library manager.

To install the library, navigate to Sketch > Include Library > Manage Libraries� Wait for the Library Manager to download the libraries index and update the list of installed libraries.

Arduino Library Installation - Selecting Manage Libraries in Arduino IDE

Filter your search by entering �DHT sensor�. Look for DHT sensor library by Adafruit. Click on that entry and then choose Install.

Adafruit DHT library Installation

The DHT sensor library makes use of the Adafruit Sensor support backend. So, look for Adafruit Unified Sensor in the library manager and install it as well.

Adafruit Unified Sensor library Installation

Creating an ESP32 Web Server using WiFi Station (STA) mode

Let�s move on to the interesting stuff now!

As the title implies, we will configure an ESP32 web server in Station (STA) mode to serve web pages to any connected client on the existing network.

Before you begin uploading the sketch, you must replace the following two variables with your network credentials so that the ESP32 can connect to an existing network.

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

When you�re finished, try out the sketch, and then we�ll go over it in detail.

#include <WiFi.h>
#include <WebServer.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

/*Put your SSID & Password*/
const char* ssid = "YourNetworkName";  // Enter SSID here
const char* password = "YourPassword";  //Enter Password here

WebServer server(80);

// DHT Sensor
uint8_t DHTPin = 4; 
               
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);                

float Temperature;
float Humidity;
 
void setup() {
  Serial.begin(115200);
  delay(100);
  
  pinMode(DHTPin, INPUT);

  dht.begin();              

  Serial.println("Connecting to ");
  Serial.println(ssid);

  //connect to your local wi-fi network
  WiFi.begin(ssid, password);

  //check wi-fi is connected to wi-fi network
  while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected..!");
  Serial.print("Got IP: ");  Serial.println(WiFi.localIP());

  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");

}
void loop() {
  
  server.handleClient();
  
}

void handle_OnConnect() {

 Temperature = dht.readTemperature(); // Gets the values of the temperature
  Humidity = dht.readHumidity(); // Gets the values of the humidity 
  server.send(200, "text/html", SendHTML(Temperature,Humidity)); 
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

String SendHTML(float Temperaturestat,float Humiditystat){
  String ptr = "<!DOCTYPE html> <html>\n";
  ptr +="<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
  ptr +="<title>ESP32 Weather Report</title>\n";
  ptr +="<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\n";
  ptr +="body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;}\n";
  ptr +="p {font-size: 24px;color: #444444;margin-bottom: 10px;}\n";
  ptr +="</style>\n";
  ptr +="</head>\n";
  ptr +="<body>\n";
  ptr +="<div id=\"webpage\">\n";
  ptr +="<h1>ESP32 Weather Report</h1>\n";
  
  ptr +="<p>Temperature: ";
  ptr +=(int)Temperaturestat;
  ptr +="�C</p>";
  ptr +="<p>Humidity: ";
  ptr +=(int)Humiditystat;
  ptr +="%</p>";
  
  ptr +="</div>\n";
  ptr +="</body>\n";
  ptr +="</html>\n";
  return ptr;
}

Accessing the Web Server

After uploading the sketch, open the Serial Monitor at 115200 baud and press the RESET button on the ESP32. If everything is fine, it will display the dynamic IP address obtained from your router as well as the �HTTP server started� message.

ESP32 Web Server Station Mode Serial Monitor Output - Server Started

Next, launch a browser and navigate to the IP address displayed on the serial monitor. The ESP32 should serve a web page with the current temperature and relative humidity.

Display DHT11 DHT22 AM2302 Temperature Humidity on ESP32 Web Server - Without CSS

Detailed Code Explanation

The sketch begins by including the WiFi.h library. This library contains ESP32-specific methods that we use to connect to the network. Following that, we include the WebServer.h library, which contains some methods that will assist us in configuring a server and handling incoming HTTP requests without having to worry about low-level implementation details. Finally, we include the DHT.h library.

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

Next, we specify the type of DHT sensor we are using. Uncomment the appropriate line below!

//#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

Because we are configuring the ESP32 web server in Station (STA) mode, it will join the existing WiFi network. So, we need to specify the SSID and password.

/*Put your SSID & Password*/
const char* ssid = "YourNetworkName";  // Enter SSID here
const char* password = "YourPassword";  //Enter Password here

Following that, we create an object of the WebServer library so that we can access its functions. The constructor of this object accepts as a parameter the port to which the server will be listening. Since HTTP uses port 80 by default, we�ll use this value. This allows us to connect to the server without specifying the port in the URL.

// declare an object of WebServer library
WebServer server(80);

Next, we define the GPIO pin number on the ESP32 to which our sensor�s Data pin is connected and create a DHT object. So, we can access DHT library-specific functions.

// DHT Sensor
uint8_t DHTPin = 4;
 
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);

There are two float variables set up: Temperature and Humidity.

float Temperature;
float Humidity;

Inside Setup() Function

In the setup function, we configure our web server. First, we establish a serial connection for debugging purposes and configure the GPIO pin to behave as an INPUT. We also initialize the DHT object.

Serial.begin(115200);
delay(100);
  
pinMode(DHTPin, INPUT);

dht.begin();

Then, we use the WiFi.begin() function to connect to the WiFi network. The function accepts SSID (Network Name) and password as parameters.

Serial.println("Connecting to ");
Serial.println(ssid);

//connect to your local wi-fi network
WiFi.begin(ssid, password);

While the ESP32 attempts to connect to the network, we can use the WiFi.status() function to check the connectivity status.

//check wi-fi is connected to wi-fi network
  while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
  }

Once connected to the network, the WiFi.localIP() function is used to print the IP address assigned to the ESP32.

Serial.println("");
  Serial.println("WiFi connected..!");
  Serial.print("Got IP: ");  Serial.println(WiFi.localIP());

To handle incoming HTTP requests, we must specify which code should be executed when a specific URL is accessed. For this, we use the .on() method. This method accepts two parameters: a relative URL path and the name of the function to be executed when that URL is visited.

The code below indicates that when a server receives an HTTP request on the root (/) path, it will call the handle_OnConnect() function. It is important to note that the URL specified is a relative path.

server.on("/", handle_OnConnect);

We haven�t specified what the server should serve if the client requests a URL that isn�t specified with server.on() . It should give a 404 error (Page Not Found) as a response. To accomplish this, we use the server.onNotFound() method.

server.onNotFound(handle_NotFound);

Now, to start the server, we call the server object�s begin() method.

server.begin();
Serial.println("HTTP server started");

Inside Loop() Function

Actual incoming HTTP requests are handled in the loop function. For this, we use the server object�s handleClient() method.

server.handleClient();

Now we must write the handle_OnConnect() function, which we previously attached to the root (/) URL with server.on. We begin this function by reading temperature and humidity values from the sensor.

We use the send method to respond to an HTTP request. Although the method can be called with a number of different arguments, the simplest form requires the HTTP response code, the content type, and the content.

The first parameter we pass to the send method is the code 200 (one of the HTTP status codes), which corresponds to the OK response. Then we specify the content type as �text/html,� and finally we pass the SendHTML() custom function, which generates a dynamic HTML page with the temperature and humidity readings.

void handle_OnConnect() 
{
  Temperature = dht.readTemperature(); // Gets the values of the temperature
  Humidity = dht.readHumidity(); // Gets the values of the humidity 
  server.send(200, "text/html", SendHTML(Temperature,Humidity)); 
}

Similarly, we write a function to handle the 404 Error page.

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

Displaying the HTML Web Page

Whenever the ESP32 web server receives a request from a web client, the sendHTML() function generates a web page. It simply concatenates HTML code into a long string and returns to the server.send() function we discussed earlier. The function uses temperature and humidity readings as parameters to generate HTML content dynamically.

The first text you should always send is the <!DOCTYPE> declaration, which indicates that we�re sending HTML code.

String SendHTML(float Temperaturestat,float Humiditystat){
String ptr = "<!DOCTYPE html> <html>\n";

The <meta> viewport element makes the web page responsive, ensuring that it looks good on all devices. The title tag determines the page�s title.

ptr +="<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
ptr +="<title>ESP32 Weather Report</title>\n";

Styling the Web Page

Following that, we have some CSS to style the overall appearance of the web page. We select the Helvetica font and define the content to be displayed as an inline-block, center-aligned.

ptr +="<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\n";

The code that follows then sets the color, font, and margin around the body, H1, and p tags.

ptr +="body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;}\n";
ptr +="p {font-size: 24px;color: #444444;margin-bottom: 10px;}\n";
ptr +="</style>\n";
ptr +="</head>\n";
ptr +="<body>\n";

Setting the Web Page Heading

Next, the heading of the web page is set. You can change this text to anything that works for your application.

ptr +="<div id=\"webpage\">\n";
ptr +="<h1>ESP32 Weather Report</h1>\n";

Displaying Temperature and Humidity on Web Page

We used the paragraph tag to display temperature and humidity values. Note that these values ??are converted to integers using type casting.

  ptr +="<p>Temperature: ";
  ptr +=(int)Temperaturestat;
  ptr +="�C</p>";
  ptr +="<p>Humidity: ";
  ptr +=(int)Humiditystat;
  ptr +="%</p>";
  
  ptr +="</div>\n";
  ptr +="</body>\n";
  ptr +="</html>\n";
  return ptr;
}

Styling Web Page to Look More Professional

Programmers have a tendency to overlook aesthetics, but with a little effort, our webpage can appear more attractive. The screenshot below will give you an idea of what we�re going to do.

Display DHT11 DHT22 AM2302 Temperature Humidity on ESP32 Web Server - Professional Look

Isn�t it incredible? Let�s add some style to our previous HTML page now. To begin, replace the SendHTML() function in the sketch above with the code below. Try out the new sketch, and then we�ll go over it in detail.

String SendHTML(float TempCstat,float TempFstat,float Humiditystat){
  String ptr = "<!DOCTYPE html> <html>\n";
  ptr +="<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
  ptr +="<link href=\"https://fonts.googleapis.com/css?family=Open+Sans:300,400,600\" rel=\"stylesheet\">\n";
  ptr +="<title>ESP32 Weather Report</title>\n";
  ptr +="<style>html { font-family: 'Open Sans', sans-serif; display: block; margin: 0px auto; text-align: center;color: #333333;}\n";
  ptr +="body{margin-top: 50px;}\n";
  ptr +="h1 {margin: 50px auto 30px;}\n";
  ptr +=".side-by-side{display: inline-block;vertical-align: middle;position: relative;}\n";
  ptr +=".humidity-icon{background-color: #3498db;width: 30px;height: 30px;border-radius: 50%;line-height: 36px;}\n";
  ptr +=".humidity-text{font-weight: 600;padding-left: 15px;font-size: 19px;width: 160px;text-align: left;}\n";
  ptr +=".humidity{font-weight: 300;font-size: 60px;color: #3498db;}\n";
  ptr +=".temperature-icon{background-color: #f39c12;width: 30px;height: 30px;border-radius: 50%;line-height: 40px;}\n";
  ptr +=".temperature-text{font-weight: 600;padding-left: 15px;font-size: 19px;width: 160px;text-align: left;}\n";
  ptr +=".temperature{font-weight: 300;font-size: 60px;color: #f39c12;}\n";
  ptr +=".superscript{font-size: 17px;font-weight: 600;position: absolute;right: -20px;top: 15px;}\n";
  ptr +=".data{padding: 10px;}\n";
  ptr +="</style>\n";
  ptr +="</head>\n";
  ptr +="<body>\n";
  
   ptr +="<div id=\"webpage\">\n";
   
   ptr +="<h1>ESP32 Weather Report</h1>\n";
   ptr +="<div class=\"data\">\n";
   ptr +="<div class=\"side-by-side temperature-icon\">\n";
   ptr +="<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n";
   ptr +="width=\"9.915px\" height=\"22px\" viewBox=\"0 0 9.915 22\" enable-background=\"new 0 0 9.915 22\" xml:space=\"preserve\">\n";
   ptr +="<path fill=\"#FFFFFF\" d=\"M3.498,0.53c0.377-0.331,0.877-0.501,1.374-0.527C5.697-0.04,6.522,0.421,6.924,1.142\n";
   ptr +="c0.237,0.399,0.315,0.871,0.311,1.33C7.229,5.856,7.245,9.24,7.227,12.625c1.019,0.539,1.855,1.424,2.301,2.491\n";
   ptr +="c0.491,1.163,0.518,2.514,0.062,3.693c-0.414,1.102-1.24,2.038-2.276,2.594c-1.056,0.583-2.331,0.743-3.501,0.463\n";
   ptr +="c-1.417-0.323-2.659-1.314-3.3-2.617C0.014,18.26-0.115,17.104,0.1,16.022c0.296-1.443,1.274-2.717,2.58-3.394\n";
   ptr +="c0.013-3.44,0-6.881,0.007-10.322C2.674,1.634,2.974,0.955,3.498,0.53z\"/>\n";
   ptr +="</svg>\n";
   ptr +="</div>\n";
   ptr +="<div class=\"side-by-side temperature-text\">Temperature</div>\n";
   ptr +="<div class=\"side-by-side temperature\">";
   ptr +=(int)TempCstat;
   ptr +="<span class=\"superscript\">�C</span></div>\n";
   ptr +="</div>\n";
   ptr +="<div class=\"data\">\n";
   ptr +="<div class=\"side-by-side humidity-icon\">\n";
   ptr +="<svg version=\"1.1\" id=\"Layer_2\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n\"; width=\"12px\" height=\"17.955px\" viewBox=\"0 0 13 17.955\" enable-background=\"new 0 0 13 17.955\" xml:space=\"preserve\">\n";
   ptr +="<path fill=\"#FFFFFF\" d=\"M1.819,6.217C3.139,4.064,6.5,0,6.5,0s3.363,4.064,4.681,6.217c1.793,2.926,2.133,5.05,1.571,7.057\n";
   ptr +="c-0.438,1.574-2.264,4.681-6.252,4.681c-3.988,0-5.813-3.107-6.252-4.681C-0.313,11.267,0.026,9.143,1.819,6.217\"></path>\n";
   ptr +="</svg>\n";
   ptr +="</div>\n";
   ptr +="<div class=\"side-by-side humidity-text\">Humidity</div>\n";
   ptr +="<div class=\"side-by-side humidity\">";
   ptr +=(int)Humiditystat;
   ptr +="<span class=\"superscript\">%</span></div>\n";
   ptr +="</div>\n";

  ptr +="</div>\n";
  ptr +="</body>\n";
  ptr +="</html>\n";
  return ptr;
}

Code Explanation

We already know that the <!DOCTYPE> declaration informs the browser that we are sending HTML code, and the <meta> viewport element makes the web page responsive. The only difference here is that we�ll be using Google Fonts. Google offers hundreds of free web fonts for commercial and personal use.

For our website, we will use the Google-commissioned Open Sans web font. The Google font is embedded in your HTML document�s head using the <link> tag.

For our page, we�ve chosen font weights of 300 (Light), 400 (Regular), and 600 (Bold). You can choose as many as you want, but keep in mind that excessive font weights slow down page load time.

You can also add italic style by simply appending an i character to the end of the font weight, for example, 400i will embed regular-italic-style-font.

It is important to note that google fonts are loaded dynamically; you will not be able to see the Google font unless you have an active internet connection on the device from which you are accessing this page.

String SendHTML(float TempCstat,float TempFstat,float Humiditystat){
String ptr = "<!DOCTYPE html> <html>\n";
ptr +="<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
ptr +="<link href=\"https://fonts.googleapis.com/css?family=Open+Sans:300,400,600\" rel=\"stylesheet\">\n";

Next, we will apply the Open Sans font to the entire HTML document. We must also specify sans-serif as our fallback font. If the first specified font fails to load, the browser will attempt to load the fallback font.

ptr +="<title>ESP32 Weather Report</title>\n";
ptr +="<style>html { font-family: 'Open Sans', sans-serif; display: block; margin: 0px auto; text-align: center;color: #333333;}\n";
ptr +="body{margin-top: 50px;}\n";
ptr +="h1 {margin: 50px auto 30px;}\n";

Next, we apply CSS for Humidity & Temperature � icons, titles, and values. All three of these elements are inline and vertically aligned. The icon background is made circular using a border radius of 50% and 30px height and width.

ptr +=".side-by-side{display: inline-block;vertical-align: middle;position: relative;}\n";
ptr +=".humidity-icon{background-color: #3498db;width: 30px;height: 30px;border-radius: 50%;line-height: 36px;}\n";
ptr +=".humidity-text{font-weight: 600;padding-left: 15px;font-size: 19px;width: 160px;text-align: left;}\n";
ptr +=".humidity{font-weight: 300;font-size: 60px;color: #3498db;}\n";
ptr +=".temperature-icon{background-color: #f39c12;width: 30px;height: 30px;border-radius: 50%;line-height: 40px;}\n";
ptr +=".temperature-text{font-weight: 600;padding-left: 15px;font-size: 19px;width: 160px;text-align: left;}\n";
ptr +=".temperature{font-weight: 300;font-size: 60px;color: #f39c12;}\n";
ptr +=".superscript{font-size: 17px;font-weight: 600;position: absolute;right: -20px;top: 15px;}\n";
ptr +=".data{padding: 10px;}\n";
ptr +="</style>\n";
ptr +="</head>\n";
ptr +="<body>\n";
Following that, we display temperature readings with this nice little icon.

The temperature icon is a Scalable Vector Graphics (SVG) image defined in the <svg> tag. Creating an SVG requires no special programming skills. You can create graphics for your page using Google SVG Editor. Following the icon, we display the actual temperature reading from the sensor.

ptr +="<div id=\"webpage\">\n";
ptr +="<h1>ESP32 Weather Report</h1>\n";
ptr +="<div class=\"data\">\n";

ptr +="<div class=\"side-by-side temperature-icon\">\n";
ptr +="<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n";
ptr +="width=\"9.915px\" height=\"22px\" viewBox=\"0 0 9.915 22\" enable-background=\"new 0 0 9.915 22\" xml:space=\"preserve\">\n";
ptr +="<path fill=\"#FFFFFF\" d=\"M3.498,0.53c0.377-0.331,0.877-0.501,1.374-0.527C5.697-0.04,6.522,0.421,6.924,1.142\n";
ptr +="c0.237,0.399,0.315,0.871,0.311,1.33C7.229,5.856,7.245,9.24,7.227,12.625c1.019,0.539,1.855,1.424,2.301,2.491\n";
ptr +="c0.491,1.163,0.518,2.514,0.062,3.693c-0.414,1.102-1.24,2.038-2.276,2.594c-1.056,0.583-2.331,0.743-3.501,0.463\n";
ptr +="c-1.417-0.323-2.659-1.314-3.3-2.617C0.014,18.26-0.115,17.104,0.1,16.022c0.296-1.443,1.274-2.717,2.58-3.394\n";
ptr +="c0.013-3.44,0-6.881,0.007-10.322C2.674,1.634,2.974,0.955,3.498,0.53z\"/>\n";
ptr +="</svg>\n";
ptr +="</div>\n";

ptr +="<div class=\"side-by-side temperature-text\">Temperature</div>\n";
ptr +="<div class=\"side-by-side temperature\">";
ptr +=(int)TempCstat;
ptr +="<span class=\"superscript\">�C</span></div>\n";
ptr +="</div>\n";
With this icon, we display humidity readings.

It�s another SVG. After printing the humidity values, we close all open tags such as body and html.

ptr +="<div class=\"data\">\n";
ptr +="<div class=\"side-by-side humidity-icon\">\n";
ptr +="<svg version=\"1.1\" id=\"Layer_2\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n\"; width=\"12px\" height=\"17.955px\" viewBox=\"0 0 13 17.955\" enable-background=\"new 0 0 13 17.955\" xml:space=\"preserve\">\n";
ptr +="<path fill=\"#FFFFFF\" d=\"M1.819,6.217C3.139,4.064,6.5,0,6.5,0s3.363,4.064,4.681,6.217c1.793,2.926,2.133,5.05,1.571,7.057\n";
ptr +="c-0.438,1.574-2.264,4.681-6.252,4.681c-3.988,0-5.813-3.107-6.252-4.681C-0.313,11.267,0.026,9.143,1.819,6.217\"></path>\n";
ptr +="</svg>\n";
ptr +="</div>\n";
ptr +="<div class=\"side-by-side humidity-text\">Humidity</div>\n";
ptr +="<div class=\"side-by-side humidity\">";
ptr +=(int)Humiditystat;
ptr +="<span class=\"superscript\">%</span></div>\n";
ptr +="</div>\n";

ptr +="</div>\n";
ptr +="</body>\n";
ptr +="</html>\n";
return ptr;
}

Improvement 1 � Auto Page Refresh

One of the improvements you can make is to automatically refresh the page in order to update the sensor value.

You can instruct the browser to automatically reload the page at a specified interval by inserting a single meta tag into your HTML document.

<meta http-equiv="refresh" content="2" >

Insert this code into your document�s <head> tag; this meta tag will instruct the browser to refresh every two seconds.

Improvement 2 � Dynamically load Sensor Data with AJAX

Refreshing a web page is impractical if the web page is large. Asynchronous Javascript And Xml (AJAX) is a better method because it allows us to request data from the server asynchronously (in the background) without refreshing the page.

The XMLHttpRequest object within JavaScript is commonly used to execute AJAX on webpages. It sends a silent GET request to the server and updates the page element. AJAX is not a new technology, nor is it a different programming language; rather, it is simply an existing technology that is used in a different way. It allows you to:

  • Request data from a server after the page has loaded
  • Receive data from a server after the page has loaded
  • Send data to a server in the background

This is the AJAX script we�ll be using. Place this script before closing the <head> tag.

ptr +="<script>\n";
ptr +="setInterval(loadDoc,200);\n";
ptr +="function loadDoc() {\n";
ptr +="var xhttp = new XMLHttpRequest();\n";
ptr +="xhttp.onreadystatechange = function() {\n";
ptr +="if (this.readyState == 4 && this.status == 200) {\n";
ptr +="document.getElementById(\"webpage\").innerHTML =this.responseText}\n";
ptr +="};\n";
ptr +="xhttp.open(\"GET\", \"/\", true);\n";
ptr +="xhttp.send();\n";
ptr +="}\n";
ptr +="</script>\n";

Code Explanation

Because the AJAX script is just javascript, it must be enclosed in the <script> tag. We�ll use the javascript setInterval() function to make this function call itself repeatedly. It requires two parameters: the function to be executed and the time interval (in milliseconds).

ptr +="<script>\n";
ptr +="setInterval(loadDoc,200);\n";

A loadDoc() function is the most important part of this script. In this function, an object of XMLHttpRequest() is created. This object is used to query a web server for data.

ptr +="function loadDoc() {\n";
ptr +="var xhttp = new XMLHttpRequest();\n";

The xhttp.onreadystatechange() method is called whenever the readyState changes. The readyState property represents the XMLHttpRequest�s status. It has one of the values listed below.

  • 0: request not initialized
  • 1: server connection established
  • 2: request received
  • 3: processing request
  • 4: request finished and response is ready

The status property holds the XMLHttpRequest object�s status. It has one of the values listed below.

  • 200: �OK�
  • 403: �Forbidden�
  • 404: �Page not found�

When readyState is 4 and status is 200, the response is complete, and the content of the element with id �webpage� (div containing temperature and humidity values) is updated.

ptr +="xhttp.onreadystatechange = function() {\n";
ptr +="if (this.readyState == 4 && this.status == 200) {\n";
ptr +="document.getElementById(\"webpage\").innerHTML =this.responseText}\n";
ptr +="};\n";

The open() and send() functions are then used to initiate the HTTP request.

ptr +="xhttp.open(\"GET\", \"/\", true);\n";
ptr +="xhttp.send();\n";
ptr +="}\n";

Login
ADS CODE