#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "Wokwi-GUEST"; // Replace with your WiFi SSID
const char* password = ""; // Replace with your WiFi password
WebServer server(80);
const int relayPin1 = 4; // GPIO pin controlling Relay 1 (Fan)
const int relayPin2 = 5; // GPIO pin controlling Relay 2 (Light)
bool fanState = false;
bool lightState = false;
void setup() {
Serial.begin(115200);
pinMode(relayPin1, OUTPUT);
pinMode(relayPin2, OUTPUT);
// Initialize relays to OFF state
digitalWrite(relayPin1, LOW);
digitalWrite(relayPin2, LOW);
// Connect to WiFi
connectToWiFi();
// Print ESP32 IP address
Serial.print("ESP32 IP address: ");
Serial.println(WiFi.localIP());
// Set up web server routes
server.on("/", HTTP_GET, [](){
// HTML code for the webpage
String webPage = "<!DOCTYPE html>\
<html>\
<head>\
<title>Home Automation</title>\
<style>\
button {\
width: 100px;\
height: 50px;\
font-size: 18px;\
}\
</style>\
</head>\
<body>\
<h1>Home Automation</h1>\
<button onclick=\"toggleFan()\">Toggle Fan</button>\
<button onclick=\"toggleLight()\">Toggle Light</button>\
<script>\
function toggleFan() {\
fetch('/toggleFan');\
}\
function toggleLight() {\
fetch('/toggleLight');\
}\
</script>\
</body>\
</html>";
server.send(200, "text/html", webPage);
});
// Route for toggling the fan
server.on("/toggleFan", HTTP_GET, [](){
fanState = !fanState; // Toggle fan state
digitalWrite(relayPin1, fanState ? HIGH : LOW); // Toggle relay pin state
server.send(200, "text/plain", "Fan Toggled"); // Send response
});
// Route for toggling the light
server.on("/toggleLight", HTTP_GET, [](){
lightState = !lightState; // Toggle light state
digitalWrite(relayPin2, lightState ? HIGH : LOW); // Toggle relay pin state
server.send(200, "text/plain", "Light Toggled"); // Send response
});
// Start the web server
server.begin();
Serial.println("Server started.");
}
void loop() {
// Handle incoming client requests
server.handleClient();
}
void connectToWiFi() {
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
attempts++;
if (attempts > 10) {
Serial.println("Failed to connect to WiFi. Please check your credentials and try again.");
break;
}
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nWiFi connected.");
}
}