#include <WiFi.h> // For ESP32 (use <ESP8266WiFi.h> for ESP8266)
#include <WebServer.h> // For creating a web server
// Wi-Fi Credentials
const char* ssid = "Wokwi-WiFi"; // Wi-Fi network name
const char* password = "12345678"; // Wi-Fi password
// Pin Definitions
const int ledPin = 2; // Built-in LED for ESP32 (use D4 for ESP8266)
// Web Server
WebServer server(80); // HTTP server on port 80
// Light State
bool lightState = false;
// Function to generate the HTML webpage
String generateHTML() {
String html = "<!DOCTYPE html><html>";
html += "<head><title>IoT Smart Light</title></head>";
html += "<body style='text-align:center; font-family:Arial;'>";
html += "<h1>IoT Smart Light Control</h1>";
html += "<p>Light is currently: <strong>" + String(lightState ? "ON" : "OFF") + "</strong></p>";
html += "<a href=\"/toggle\" style='display:inline-block; padding:10px 20px; background:#007BFF; color:white; text-decoration:none; border-radius:5px;'>Toggle Light</a>";
html += "</body></html>";
return html;
}
// Handle root URL
void handleRoot() {
server.send(200, "text/html", generateHTML());
}
// Handle light toggle
void handleToggle() {
lightState = !lightState;
digitalWrite(ledPin, lightState ? HIGH : LOW);
server.send(200, "text/html", generateHTML());
}
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // Turn off LED initially
Serial.begin(115200); // Start serial monitor
Serial.println("Starting...");
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP()); // Print IP address
// Start the web server
server.on("/", handleRoot);
server.on("/toggle", handleToggle);
server.begin();
Serial.println("Web server started.");
}
void loop() {
server.handleClient(); // Handle HTTP requests
}