#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define DHT_PIN 2
#define DHT_TYPE DHT11
DHT dht(DHT_PIN, DHT_TYPE);
WebServer server(80);
unsigned long lastSensorRead = 0;
const long sensorInterval = 2000;
float temperature = 0;
float humidity = 0;
void setup() {
Serial.begin(115200);
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, handleRoot);
server.begin();
}
void loop() {
server.handleClient();
unsigned long currentMillis = millis();
if (currentMillis - lastSensorRead >= sensorInterval) {
lastSensorRead = currentMillis;
readSensor();
}
}
void readSensor() {
float newTemp = dht.readTemperature();
float newHum = dht.readHumidity();
if (!isnan(newTemp) && !isnan(newHum)) {
temperature = newTemp;
humidity = newHum;
}
}
void handleRoot() {
String html = "<html><body>";
html += "<h1>ESP32 DHT11 Sensor Readings</h1>";
if (isnan(temperature) || isnan(humidity)) {
html += "<p>Failed to read from DHT sensor</p>";
} else {
html += "<p>Temperature: " + String(temperature) + " °C</p>";
html += "<p>Humidity: " + String(humidity) + " %</p>";
}
html += "<p><a href='/'>Refresh</a></p>";
html += "</body></html>";
server.send(200, "text/html", html);
}