#include <WiFi.h>
#include <WebServer.h>
// Replace with your network credentials
const char* ssid = "akash";
const char* password = "63513696773";
// Set the GPIO pin for the relay
const int relayPin = 4;
// Create a web server object that listens for HTTP requests on port 80
WebServer server(80);
// HTML content for the web page
const char* htmlPage = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Bulb Control</title>
</head>
<body>
<h1>Bulb Control</h1>
<button onclick="toggleBulb('on')">Turn On</button>
<button onclick="toggleBulb('off')">Turn Off</button>
<script>
function toggleBulb(state) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/bulb?state=" + state, true);
xhr.send();
}
</script>
</body>
</html>
)rawliteral";
// Handle requests to root URL "/"
void handleRoot() {
server.send(200, "text/html", htmlPage);
}
// Handle requests to "/bulb" URL
void handleBulb() {
String state = server.arg("state");
if (state == "on") {
digitalWrite(relayPin, LOW); // LOW to turn on the relay (depends on your relay module)
} else if (state == "off") {
digitalWrite(relayPin, HIGH); // HIGH to turn off the relay (depends on your relay module)
}
server.send(200, "text/plain", "OK");
}
void setup() {
// Initialize serial and wait for port to open
Serial.begin(115200);
// Initialize the relay pin as an output
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, HIGH); // Ensure relay is off
// Connect to Wi-Fi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Set up web server routes
server.on("/", handleRoot);
server.on("/bulb", handleBulb);
// Start the web server
server.begin();
Serial.println("HTTP server started");
}
void loop() {
// Handle client requests
server.handleClient();
}