#include <WiFi.h> // Use <WiFi.h> for ESP32
#include <WebServer.h> // Use <WebServer.h> for ESP32
#include <DHT.h> // Include only if using DHT sensor
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Web server on port 80
WebServer server(80); // Use WebServer for ESP32
// LED Pin
const int ledPin = 2; // GPIO 2 for ESP32
// DHT Sensor (Optional)
#define DHTPIN 15 // GPIO 15 for ESP32
#define DHTTYPE DHT22// DHT22 if you're using that sensor
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
// Set up the LED pin as an output
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // LED off
// Initialize DHT sensor
dht.begin();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi..");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
// Display IP address
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// Define web server routes
server.on("/", handleRoot);
server.on("/led/on", handleLedOn);
server.on("/led/off", handleLedOff);
server.on("/data", handleSensorData);
// Start the server
server.begin();
Serial.println("Web server started");
}
void handleRoot() {
String html = "<h1>ESP Web Server</h1><p><a href=\"/led/on\"><button>Turn LED ON</button></a></p><p><a href=\"/led/off\"><button>Turn LED OFF</button></a></p><p><a href=\"/data\"><button>Get Sensor Data</button></a></p>";
server.send(200, "text/html", html);
}
// Turn LED ON
void handleLedOn() {
digitalWrite(ledPin, HIGH);
server.send(200, "text/html", "<h1>LED is ON</h1><p><a href=\"/\"><button>Back</button></a></p>");
}
// Turn LED OFF
void handleLedOff() {
digitalWrite(ledPin, LOW);
server.send(200, "text/html", "<h1>LED is OFF</h1><p><a href=\"/\"><button>Back</button></a></p>");
}
// Sensor Data (Optional)
void handleSensorData() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
server.send(500, "text/plain", "Failed to read from DHT sensor");
return;
}
String data = "<h1>Sensor Data</h1><p>Temperature: " + String(t) + " °C</p><p>Humidity: " + String(h) + " %</p><p><a href=\"/\"><button>Back</button></a></p>";
server.send(200, "text/html", data);
}
void loop() {
server.handleClient(); // Listen for incoming clients
}