#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Instantiate server at port 80 (http port)
WebServer server(80);
// DHT sensor configuration
#define DHTPIN 14 // Pin to which the data pin is connected
#define DHTTYPE DHT22 // Change to DHT11 if using that model
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
dht.begin(); // Initialize DHT sensor
WiFi.begin(ssid, password); // Begin WiFi connection
Serial.println("Connecting to WiFi...");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Setup web server handler
server.on("/", []() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
String page; // Declare the page variable
// Check if any reads failed
if (isnan(temperature) || isnan(humidity)) {
page = "<h1><center>Failed to read from DHT sensor!</center></h1>";
} else {
page = "<h1><center>Webpage Monitoring Using ESP32</center></h1>"
"<h3><center>Temperature: " + String(temperature) + " °C</center></h3>"
"<h3><center>Humidity: " + String(humidity) + " %</center></h3>";
}
server.send(200, "text/html", page);
});
server.begin();
Serial.println("Web server started!");
}
void loop() {
server.handleClient();
delay(500);
}