//Change Line Nos.3,7,28
//Wokwi
#include "WiFi.h"
//#include <ESP8266WiFi.h> //NodeMCU
#include <WiFiClient.h>
#include "DHT.h"
#define DHTPIN 2 //D2
//Wokwi
//#define DHTPIN 4 //D2
#define DHTTYPE DHT11
DHT dht (DHTPIN, DHTTYPE);
WiFiServer server(80);
//NodeMCU
static char celsius [7];
static char fahrenheit [7];
static char humidity[7];
void setup() {
Serial.begin(9600);
dht.begin();
WiFi.mode (WIFI_STA);
WiFi.begin("Wokwi-GUEST", "");
//WiFi.begin("ssid","pw");
Serial.println("");
while (WiFi.status() != WL_CONNECTED) {
delay(5000);
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(); //Celsius
float f = dht.readTemperature (true); //Fahrenheit
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.println("F");
}
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("</h3><h3>Humidity: ");
client.println(humidity);
client.println("</h3><h3>");
client.println("</body></html>");
break;
}
if (c == '\n') {
blank_line = true;
}
else if (c != '\n') {
blank_line = false;
}
}
}
delay(2);
client.stop();
Serial.println("Client disconnected.");
}
}