#include "WiFi.h"
//#include "ESPAsyncTCP.h"
#include "ESPAsyncWebSrv.h"
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN,DHTTYPE);
AsyncWebServer server(80);
float t = 0.0;
float h = 0.0;
unsigned long previousMillis = 0;
const long interval = 10000;
const char index_html[] PROGMEM = R"=====(
<!DOCTYPE HTML><html>
<head>
<meta name ="viewport" content = "width=device-width,initial-scale=1">
<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 Srever</h2>
<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 = "temperature"> %HUMIDITY%</span>
<sup class ="units">%</sup>
</p>
<script>
setInterval(function( ){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState == 4 && this.status ==200){
document.getElementById("temperature").innerHTML=thisHTML= this.responseText;
}
};
xhttp.open("GET","/temperature",true);
xhttp.send();
},1000 );
setInterval(function( ){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState == 4 && this.status ==200){
document.getElementById("humidity").innerHTML=thisHTML= this.responseText;
}
};
xhttp.open("GET","/humidity",true);
xhttp.send();
},1000 );
</script>
</html>)=====";
String processor(const String& var ){
if (var == "TEMPERATURE"){
return String(t);
}
else if(var== "HUMIDITY"){
return String(h);
}
return String();
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
dht.begin();
WiFi.mode(WIFI_STA);
WiFi.begin(("Wokwi-GUEST",""));
Serial.println("");
while (WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WIFI Connected");
Serial.print("IP address:");
Serial.println(WiFi.localIP());
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.begin();
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis>=interval)
{
previousMillis=currentMillis;
float newT = dht.readTemperature();
if(isnan(newT)){
Serial.println("Failed to read from DHT sensor");
}
else {
t=newT;
Serial.println(t);
}
float newH = dht.readHumidity();
if(isnan(newH)){
Serial.println("Failed to read from DHT sensor");
}
else {
h=newH;
Serial.println(h);
}
}
}