#include <WiFiManager.h> // For WiFi management
#include <WebServer.h> // For the web server
// Define LED pins
const int ledPin1 = 12; // GPIO 12 for LED 1
const int ledPin2 = 14; // GPIO 14 for LED 2
WebServer server(80); // Create an instance of the server on port 80
void setup() {
// Start Serial Monitor
Serial.begin(115200);
// Initialize LEDs as OUTPUT
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
// Initialize Wi-Fi manager
WiFiManager wifiManager;
// Attempt to connect to Wi-Fi network. If not connected, create an access point
if (!wifiManager.autoConnect("ESP32-LED-AP")) {
Serial.println("Failed to connect to Wi-Fi. Restarting...");
ESP.restart(); // Restart if Wi-Fi connection fails
}
Serial.println("Connected to Wi-Fi");
Serial.println(WiFi.localIP()); // Print the local IP address of the ESP32
// Setup routes for the web server
server.on("/", HTTP_GET, []() {
String html = "<html><body>";
html += "<h1>ESP32 LED Control</h1>";
html += "<p><a href=\"/led1/on\"><button>Turn LED 1 ON</button></a> ";
html += "<a href=\"/led1/off\"><button>Turn LED 1 OFF</button></a></p>";
html += "<p><a href=\"/led2/on\"><button>Turn LED 2 ON</button></a> ";
html += "<a href=\"/led2/off\"><button>Turn LED 2 OFF</button></a></p>";
html += "</body></html>";
server.send(200, "text/html", html); // Send HTML page to client
});
// Define LED 1 control
server.on("/led1/on", HTTP_GET, []() {
digitalWrite(ledPin1, HIGH); // Turn LED 1 ON
server.sendHeader("Location", "/"); // Redirect to the main page
server.send(303);
});
server.on("/led1/off", HTTP_GET, []() {
digitalWrite(ledPin1, LOW); // Turn LED 1 OFF
server.sendHeader("Location", "/"); // Redirect to the main page
server.send(303);
});
// Define LED 2 control
server.on("/led2/on", HTTP_GET, []() {
digitalWrite(ledPin2, HIGH); // Turn LED 2 ON
server.sendHeader("Location", "/"); // Redirect to the main page
server.send(303);
});
server.on("/led2/off", HTTP_GET, []() {
digitalWrite(ledPin2, LOW); // Turn LED 2 OFF
server.sendHeader("Location", "/"); // Redirect to the main page
server.send(303);
});
// Start the server
server.begin();
Serial.println("HTTP Server started");
}
void loop() {
// Handle incoming client requests
server.handleClient();
}