#include <AsyncWebSocket.h>
#include <AsyncWebSynchronization.h>
#include <ESPAsyncWebServer.h>
//#include <SPIFFSEditor.h>
#include <StringArray.h>
#include <WebAuthentication.h>
#include <WebHandlerImpl.h>
#include <WebResponseImpl.h>
#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
const char* ssid = "MI 14.0.3";
const char* password = "123456pL";
#define DHTPIN D5 // 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;
float m = 0.0;
int MOISTURE_PIN = A0;
// 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
/* DISPLAY VARIOUS MEASUREMENTS ON WEBPAGE*/
// 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>Smart Agriculture</h2>
<p>
<i class="fas fa-water" style="color:#00aed6;"></i>
<span class="dht-labels">Moisture</span>
<span id="moisture">%MOISTURE%</span>
<sup class="units">θ</sup>
</p>
<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">°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 ) ;
setInterval(function ( )
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("moisture").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/moisture", true);
xhttp.send();
}, 10000 ) ;
</script>
</html>)rawliteral";
/* DISPLAY OF CHARTS FOR VARIOUS MEASUREMENTS ON THE WEBPAGE*/
<!DOCTYPE HTML><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.highcharts.com/highcharts.js"></script>
<style>
body
{
min-width: 310px;
max-width: 800px;
height: 400px;
margin: 0 auto;
}
h2
{
font-family: Arial;
font-size: 2.5rem;
text-align: center;
}
</style>
</head>
<body>
<h2>ESP Weather Station</h2>
<div id="chart-temperature" class="container"></div>
<div id="chart-humidity" class="container"></div>
<div id="chart-pressure" class="container"></div>
</body>
<script>
/* TEMPERATURE MEASUREMENT WITH DH22*/
setInterval(function ()
{
var xhttp = new XMLHttpRequest(); // Creates a new XMLHttpRequest object for making HTTP requests
xhttp.onreadystatechange = function () // Defines a function to handle state changes of the XMLHttpRequest
{
if (this.readyState == 4 && this.status == 200) // Checks if the request is complete and successful
{
var x = (new Date()).getTime(), // Gets the current timestamp for the x-axis
y = parseFloat(this.responseText); // Parses the temperature value from the response
// Checks if the length of the data series exceeds 40 points
if (chartT.series[0].data.length > 40)
{
chartT.series[0].addPoint([x, y], true, true, true); // Adds a new data point to the chart, removing the oldest point if necessary
}
else
{
chartT.series[0].addPoint([x, y], true, false, true); // Adds a new data point to the chart without removing the oldest point
}
}
};
xhttp.open("GET", "/temperature", true); // Specifies the HTTP method, URL, and asynchronous flag for the request
xhttp.send(); // Sends the HTTP request to fetch temperature data from the server
}, 30000); // Sets the interval for fetching data every 30 seconds (30000 milliseconds)
/* Initialize a Highcharts chart temperature object*/
var chartT = new Highcharts.Chart({
// Chart container configuration
chart: { renderTo: 'chart-temperature' }, // Render the chart to the HTML element with ID 'chart-temperature'
// Chart title configuration
title: { text: 'DHT22 Temperature' }, // Set the title of the chart to 'DHT22 Temperature'
// Data series configuration
series: [{
showInLegend: false, // Do not show this series in the legend
data: [] // Initialize the data array for the series
}],
// Plot options configuration
plotOptions:
{
line:
{ // Configuration for line series
animation: false, // Disable animation for the line chart
dataLabels: { enabled: true } // Enable data labels to display values on the chart
},
series: { color: '#059e8a' } // Set the color of the series to '#059e8a'
},
// X-axis configuration
xAxis:
{
type: 'datetime', // Set the type of the X-axis to 'datetime' for time-based data
dateTimeLabelFormats: { second: '%H:%M:%S' } // Format the datetime labels to display hours, minutes, and seconds
},
// Y-axis configuration
yAxis:
{
title: { text: 'Temperature (Celsius)' } // Set the title of the Y-axis to 'Temperature (Celsius)'
//title: { text: 'Temperature (Fahrenheit)' } // Alternative title for Y-axis in Fahrenheit
},
// Credits configuration
credits: { enabled: false } // Disable Highcharts.com credits
});
/* HUMIDITY MEASUREMENT WITH DH22*/
setInterval(function ()
{
var xhttp = new XMLHttpRequest(); // Creates a new XMLHttpRequest object for making HTTP requests
xhttp.onreadystatechange = function () // Defines a function to handle state changes of the XMLHttpRequest
{
if (this.readyState == 4 && this.status == 200) // Checks if the request is complete and successful
{
var x = (new Date()).getTime(), // Gets the current timestamp for the x-axis
y = parseFloat(this.responseText); // Parses the temperature value from the response
// Checks if the length of the data series exceeds 40 points
if (chartH.series[0].data.length > 40)
{
chartH.series[0].addPoint([x, y], true, true, true); // Adds a new data point to the chart, removing the oldest point if necessary
}
else
{
chartH.series[0].addPoint([x, y], true, false, true); // Adds a new data point to the chart without removing the oldest point
}
}
};
xhttp.open("GET", "/humidity", true); // Specifies the HTTP method, URL, and asynchronous flag for the request
xhttp.send(); // Sends the HTTP request to fetch temperature data from the server
}, 30000); // Sets the interval for fetching data every 30 seconds (30000 milliseconds)
/* Initialize a Highcharts chart humidity object*/
var chartT = new Highcharts.Chart({
// Chart container configuration
chart: { renderTo: 'chart-humidity' }, // Render the chart to the HTML element with ID 'chart-humidity'
// Chart title configuration
title: { text: 'DHT22 Humidity' }, // Set the title of the chart to 'DHT22 Temperature'
// Data series configuration
series: [{
showInLegend: false, // Do not show this series in the legend
data: [] // Initialize the data array for the series
}],
// Plot options configuration
plotOptions:
{
line:
{ // Configuration for line series
animation: false, // Disable animation for the line chart
dataLabels: { enabled: true } // Enable data labels to display values on the chart
},
series: { color: '#059e8a' } // Set the color of the series to '#059e8a'
},
// X-axis configuration
xAxis:
{
type: 'datetime', // Set the type of the X-axis to 'datetime' for time-based data
dateTimeLabelFormats: { second: '%H:%M:%S' } // Format the datetime labels to display hours, minutes, and seconds
},
// Y-axis configuration
yAxis:
{
title: { text: 'Humidity (Percentage)' } // Set the title of the Y-axis to Humidity (Percentage)
},
// Credits configuration
credits: { enabled: false } // Disable Highcharts.com credits
});
/* MOISTURE MEASUREMENT WITH CAPACITIVE MOISTURE SENSOR*/
setInterval(function ()
{
var xhttp = new XMLHttpRequest(); // Creates a new XMLHttpRequest object for making HTTP requests
xhttp.onreadystatechange = function () // Defines a function to handle state changes of the XMLHttpRequest
{
if (this.readyState == 4 && this.status == 200) // Checks if the request is complete and successful
{
var x = (new Date()).getTime(), // Gets the current timestamp for the x-axis
y = parseFloat(this.responseText); // Parses the temperature value from the response
// Checks if the length of the data series exceeds 40 points
if (chartM.series[0].data.length > 40)
{
chartM.series[0].addPoint([x, y], true, true, true); // Adds a new data point to the chart, removing the oldest point if necessary
}
else
{
chartM.series[0].addPoint([x, y], true, false, true); // Adds a new data point to the chart without removing the oldest point
}
}
};
xhttp.open("GET", "/moisture", true); // Specifies the HTTP method, URL, and asynchronous flag for the request
xhttp.send(); // Sends the HTTP request to fetch temperature data from the server
}, 30000); // Sets the interval for fetching data every 30 seconds (30000 milliseconds)
/* Initialize a Highcharts chart moisture object*/
var chartT = new Highcharts.Chart({
// Chart container configuration
chart: { renderTo: 'chart-moisture' }, // Render the chart to the HTML element with ID 'chart-moisture'
// Chart title configuration
title: { text: 'capacitive moisture sensor' }, // Set the title of the chart to 'capacitive moisture sensor'
// Data series configuration
series: [{
showInLegend: false, // Do not show this series in the legend
data: [] // Initialize the data array for the series
}],
// Plot options configuration
plotOptions:
{
line:
{ // Configuration for line series
animation: false, // Disable animation for the line chart
dataLabels: { enabled: true } // Enable data labels to display values on the chart
},
series: { color: '#059e8a' } // Set the color of the series to '#059e8a'
},
// X-axis configuration
xAxis:
{
type: 'datetime', // Set the type of the X-axis to 'datetime' for time-based data
dateTimeLabelFormats: { second: '%H:%M:%S' } // Format the datetime labels to display hours, minutes, and seconds
},
// Y-axis configuration
yAxis:
{
title: { text: 'moisture (wfv)' } // Set the title of the Y-axis to moisture (water fraction by volume (wfv))
},
// Credits configuration
credits: { enabled: false } // Disable Highcharts.com credits
});
</script>
</html>
// Replaces placeholder with DHT values
String processor(const String& var)
{
//Serial.println(var);
if(var == "MOISTURE")
{
return String(m);
}
else if(var == "TEMPERATURE")
{
return String(t);
}
else if(var == "HUMIDITY")
{
return String(h);
}
else if(var == "MOISTURE")
{
return String(m);
}
return String();
}
void setup(){
// Serial port for debugging purposes
Serial.begin(115200);
dht.begin();
pinMode(A0,INPUT);
// 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());
});
server.on("/moisture", HTTP_GET, [](AsyncWebServerRequest *request)
{
request->send_P(200, "text/plain", String(m).c_str());
});
// Start server
server.begin();
}
void loop()
{
delay(1000);
float newT = dht.readTemperature();
float hum = dht.readHumidity(); // Get Humidity value
float temp= dht.readTemperature(); // Get Temperature value
float moist = analogRead(MOISTURE_PIN);
/* DISPLAY OF VARIOUS MEASUREMENTS ON THE SERIAL MONITOR*/
Serial.print("Humid:");
Serial.print( hum);
Serial.println(" % ");
Serial.print("Temp:");
Serial.print( temp);
Serial.println(" C ");
Serial.print("Moisture : ");
Serial.println(moist);
t = temp;
h = hum;
m = moist;
delay(1000);
}