#include "WiFi.h"
#include <WiFiClient.h>
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
WiFiServer server(80);
//Yaswanth Reddy-21126
static char celsius[7];
static char fahrenheit[7];
static char humidity[7];
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.begin();
Serial.println("HTTP server started");
}
void loop() {
WiFiClient client = server.available();
if (client){
Serial.println("New client");
boolean blank_line = true;
while(client.connected()){
if(client.available()){
char c = client.read();
if(c=='\n' && blank_line){
delay(2000);
float h = dht.readHumidity();
float c = dht.readTemperature();
float f = dht.readTemperature(true);
if(isnan(h) || isnan(c) || isnan(f)){
Serial.println("Failed to read from DHT11 sensor!");
strcpy(celsius,"Failed");
strcpy(fahrenheit, "Failed");
strcpy(humidity, "Failed");
}
else{
float hif = dht.computeHeatIndex(f, h);
dtostrf(f, 6, 2, fahrenheit);
float hic = dht.computeHeatIndex(c, h, false);
dtostrf(c, 6, 2, celsius);
dtostrf(h, 6, 2, humidity);
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% Temperature: ");
Serial.print(celsius);
Serial.print("°C ");
Serial.print(fahrenheit);
Serial.print("F Heat index: ");
Serial.print(hic);
Serial.print("°C ");
Serial.print(hif);
Serial.print("F");
Serial.println("");
}
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head></head><body><h1>ESP8266 - Temperature and Humidity</h1><h3>Temperature in Celsius: ");
client.println(celsius);
client.println("°C</h3><h3>Temperature in Fahrenheit: ");
client.println(fahrenheit);
client.println("F</h3><h3>Humidity: ");
client.println(humidity);
client.println("%</h3>");
client.println("</body></html>");
break;
}
if(c=='\n'){
blank_line = true;
}
else if (c!='\r'){
blank_line = false;
}
}
}
delay(2);
client.stop();
Serial.println("Client disconnected.");
}
}