ESP8266 Temperature and Humidity AsynchronousWeb Server with Arduino IDE - Black keyhole

welcome to our keyhole, we provide you various knowledge from various sources such as Electric&Electronic, Health, Arduino, IOT, Diy projects, A/l past paper and model paper, Even though you can keep in touch with current technology

ESP8266 Temperature and Humidity AsynchronousWeb Server with Arduino IDE

Share This



In this tutorial I will show you how to make web server with an ESP8266 that displays the temperature and humidity with a DHT11 or DHT22 sensor using the Arduino IDE.you don't need to refresh the web page to update the the values that updates the temperature and humidity automatically without the need to refresh the web page and with custom CSS to style the web page. Also you can access the web page from
any  of  the browser that you use, by typing the IP address.



You need following parts to build this project
  •    DH11 Sensor module (if you use DH11/DH22 Sensor with 4 pins, you need to use Resistor that will show in bellow Circuit)
  •  ESP8266(NodeMCU)
  • Jumper wires.



   In this example, I have wired the DHT data pin to GPIO5 (D1), but you can use any other suitable GPIO pin.


To make this project you need following libraries:
 1.  DHT library from Adafruit.: To read the DHT sensor, Can get the libraries from by accessing Arduion IDE then click Sketch Include Library > Manage Libraries. The Library Manager should open. Put the words in the search box as DHT then you can find the library and click  the Install button for Install the library.

2.To use DHT library you also need to install the Adafruit Unified Sensor library
  Can get the library through your Arduino IDE's library manager, where I have instructed the way in above text.


3.ESPAsyncWebServer library :It provides an easy way to build an asynchronous web server. also it provides several advantages to use. This library is not Available in Arduino IDE. So you Can ad zip file through your Arduino IDE to install in your library folder. After install this library access your Arduino library directory then delete the name "master". which is captioned with the name of  ESPAsyncWebServer.

4. ESPAsyncTCP library: ESPAsyncWebServer library requires this library to work. This library is not Available in Arduino IDE. So you Can ad zip file through your Arduino IDE to install in your library folder. After install this library access your Arduino library directory then delete the name "master". which is captioned with the name of  ESPAsyncTCP.

I will use ESP8266 using Arduino IDE. So you must have the ESP8266 in your Arduino IDE.



CODE


#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <Hash.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>

// Replace with your network credentials
//for more projects visit www.Blackkeyhole.com
const char* ssid = "YOUR network name";
const char* password = "Password";

#define DHTPIN 5     // Digital pin connected to the DHT sensor

// Uncomment the type of sensor in use:
#define DHTTYPE    DHT11     // DHT 11

DHT dht(DHTPIN, DHTTYPE);

// current temperature & humidity, updated in loop()
float t = 0.0;
float h = 0.0;

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;    // will store last time DHT was updated

// Updates DHT readings every 10 seconds
const long interval = 10000;  

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <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; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .dht-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 15px;
    }
  </style>
</head>
<body>
  <h2>ESP8266 DHT Server</h2>
  <a href="https://www.youtube.com/channel/UCEIUbi1n2LqyNOl97c-InAQ"
target="_blank">VISIT Blackkeyhole for more projects</a>
  <p>
    <i class="fas fa-thermometer-half"  style="color:#059e8a;"></i>
    <span class="dht-labels">Temperature</span> 
    <span id="temperature">%TEMPERATURE%</span>
    <sup class="units">&deg;C</sup>
  </p>
  <p>
    <i class="fas fa-tint" style="color:#00add6;"></i> 
    <span class="dht-labels">Humidity</span>
    <span 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 String(t);
  }
  else if(var == "HUMIDITY"){
    return String(h);
  }
  return String();
}

void setup(){
  // Serial port for debugging purposes
  Serial.begin(115200);
  dht.begin();
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println(".");
  }

  // Print ESP8266 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"String(t).c_str());
  });
  server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200"text/plain"String(h).c_str());
  });

  // Start server
  server.begin();
}
 
void loop(){  
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    // save the last time you updated the DHT values
    previousMillis = currentMillis;
    // Read temperature as Celsius (the default)
    float newT = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    //float newT = dht.readTemperature(true);
    // if temperature read failed, don't change t value
    if (isnan(newT)) {
      Serial.println("Failed to read from DHT sensor!");
    }
    else {
      t = newT;
      Serial.println(t);
    }
    // Read Humidity
    float newH = dht.readHumidity();
    // if humidity read failed, don't change h value 
    if (isnan(newH)) {
      Serial.println("Failed to read from DHT sensor!");
    }
    else {
      h = newH;
      Serial.println(h);
    }
  }
}



How the Code Works

         In the following paragraphs we’ll explain how the code works.

Importing the required libraries         
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <Hash.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
  
Replace your Network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

I have defined that digital pin D1(GPIO 5) is connected to the DHT sensor. here I have used DH11 sensor. So I've defined the type. if you use another type, Uncomment the type of sensor in use. then I've Instantiated a DHTobject with the type and pin defined earlier and created the flot variables to hold the temperature and huminity values.

#define DHTPIN 5    // Digital pin connected to the DHT sensor

// Uncomment the type of sensor in use:
#define DHTTYPE    DHT11     // DHT 11
//#define DHTTYPE    DHT22     // DHT 22 (AM2302)
//#define DHTTYPE    DHT21     // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

// current temperature & humidity, updated in loop()
float t = 0.0;
float h = 0.0;
  

Create an AsyncWebServerobject on port 80

AsyncWebServer server(80);

Updates DHT readings every 10 seconds

unsigned long previousMillis = 0;    // will store last time DHT was updated

// Updates DHT readings every 10 seconds
const long interval = 10000;

<meta> tag makes your web page responsive in any browser.

<meta name="viewport" content="width=device-width, initial-scale=1">



The <link> tag is needed to load the icons from the fontawesome website.
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/
all.css"integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpv
LbHG9Sr" crossorigin="anonymous">
Between the <style> </style>, have added some style for the webpage

<style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 { font-size: 3.0rem; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .dht-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 15px;
    }
  </style>


Between the <body></body> tag, have designed the web page content. 
<body>
  <h2>ESP8266 DHT Server</h2>
  <h3>www.Blackkeyhole.com</h3>
  <p>
    <i class="fas fa-thermometer-half"  style="color:#059e8a;"></i>
    <span class="dht-labels">Temperature</span> 
    <span id="temperature">%TEMPERATURE%</span>
    <sup class="units">&deg;C</sup>
  </p>
  <p>
    <i class="fas fa-tint" style="color:#00add6;"></i> 
    <span class="dht-labels">Humidity</span>
    <span id="humidity">%HUMIDITY%</span>
    <sup class="units">%</sup>
  </p>
</body>

How to display icons

        
  •  Search the icon you’re looking for. For example, “thermometer”.
  • Click the desired icon. Then, you just need to copy the HTML text provided
  • To chose the color, you just need to pass the style parameter with the color in hexadecimal, as follows.

<i class="fas fa-thermometer-half"  style="color:#059e8a;"></i>



These Jave Script codes use to update the temperature and huminity automatically, every 10 seconds.

<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>


These lines of codes are used as follows, to connect the Wifi, print the IP Address, Route for web page and start the server.

void setup(){
  // Serial port for debugging purposes
  Serial.begin(115200);
  dht.begin();
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println(".");
  }

  // Print ESP8266 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"String(t).c_str());
  });
  server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200"text/plain"String(h).c_str());
  });

  // Start server
  server.begin();
}


To read the temperature and huminity values

 
void loop(){  
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    // save the last time you updated the DHT values
    previousMillis = currentMillis;
    // Read temperature as Celsius (the default)
    float newT = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    //float newT = dht.readTemperature(true);
    // if temperature read failed, don't change t value
    if (isnan(newT)) {
      Serial.println("Failed to read from DHT sensor!");
    }
    else {
      t = newT;
      Serial.println(t);
    }
    // Read Humidity
    float newH = dht.readHumidity();
    // if humidity read failed, don't change h value 
    if (isnan(newH)) {
      Serial.println("Failed to read from DHT sensor!");
    }
    else {
      h = newH;
      Serial.println(h);
    }
  }
}




Uploading the code

    Finaly, Select the correct COM port and rigth board for upload the  code in your ESP8266. Then   hit the upload button. when the upload procces finish, open the Serial Monitor at a baud rate of 115200. Press the ESP8266 reset button. The ESP8266 IP address will be printed in the serial monitor. Paste that IP Address in any of your webbrowser. You will see the output at there. Where you could see in my above You Tube video. If you want further details, you can also follow my You Tube tutorials.



Hope you have liked this post. Please Share it  with your friend or family members who aspired to make these kind of stuf😉. 














No comments:

Post a Comment

Pages