#include <WiFi.h>
#include <ESPAsyncWebServer.h>
// Replace with your Wi-Fi credentials
const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";
// Create an AsyncWebServer object on port 80
AsyncWebServer server(80);
// Define LED pins
const int led1Pin = 2; // GPIO2 for LED1
const int led2Pin = 4; // GPIO4 for LED2
// LED states
bool led1State = false;
bool led2State = false;
// HTML webpage with CSS animations
const char webpage[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<title>ESP32 LED Control</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #f4f4f9;
margin: 0;
padding: 0;
}
h1 {
color: #333;
}
button {
background-color: #6200ea;
color: white;
border: none;
padding: 15px 30px;
font-size: 16px;
margin: 10px;
border-radius: 8px;
cursor: pointer;
transition: transform 0.2s, background-color 0.3s, box-shadow 0.3s;
}
button:hover {
background-color: #3700b3;
transform: scale(1.1);
box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.2);
}
button:active {
transform: scale(1.05);
}
p {
font-size: 18px;
color: #555;
}
</style>
</head>
<body>
<h1>ESP32 LED Control</h1>
<p>Click the buttons below to control the LEDs:</p>
<button onclick="toggleLED('led1')">Toggle LED 1</button>
<p id="status1">LED 1 is OFF</p>
<button onclick="toggleLED('led2')">Toggle LED 2</button>
<p id="status2">LED 2 is OFF</p>
<script>
function toggleLED(led) {
fetch('/toggle?led=' + led)
.then(response => response.text())
.then(status => {
if (led === 'led1') {
document.getElementById('status1').innerText = "LED 1 is " + status;
} else if (led === 'led2') {
document.getElementById('status2').innerText = "LED 2 is " + status;
}
});
}
</script>
</body>
</html>
)rawliteral";
void setup() {
Serial.begin(115200);
// Initialize LED pins
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
digitalWrite(led1Pin, LOW);
digitalWrite(led2Pin, LOW);
// Connect to Wi-Fi
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nWi-Fi connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// Serve the webpage
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/html", webpage);
});
// Handle LED toggle requests
server.on("/toggle", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request->hasParam("led")) {
String ledParam = request->getParam("led")->value();
if (ledParam == "led1") {
led1State = !led1State;
digitalWrite(led1Pin, led1State ? HIGH : LOW);
request->send(200, "text/plain", led1State ? "ON" : "OFF");
} else if (ledParam == "led2") {
led2State = !led2State;
digitalWrite(led2Pin, led2State ? HIGH : LOW);
request->send(200, "text/plain", led2State ? "ON" : "OFF");
} else {
request->send(400, "text/plain", "Invalid LED");
}
} else {
request->send(400, "text/plain", "Missing parameter");
}
});
// Start the server
server.begin();
}
void loop() {
}