En este proyecto se tiene como finalidad controlar un led desde un navegador, donde el ESP32 estará conectado a internet. Al ingresar a la página HTML se mostrará una interfaz gráfica donde se puede controlar el LED.
/*
Creado: Luis Alvarez (edualv1723@gmail.com)
https://alvelectronics.com
*/
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "TuSSID"; // Cambia por el nombre de tu red WiFi
const char* password = "TuPassword"; // Cambia por la contraseña
WebServer server(80);
const int ledPin = 2; // Pin donde está conectado el LED (generalmente GPIO 2 para el LED integrado)
void handleRoot() {
// Página web simple con dos botones para encender y apagar el LED
String html = "Control LED ESP32 ";
html += "Control de LED por WiFi - ESP32
";
html += "LED está: ";
html += digitalRead(ledPin) ? "Encendido" : "Apagado";
html += "
";
html += "";
html += "";
html += "";
server.send(200, "text/html", html);
}
void handleLedOn() {
digitalWrite(ledPin, HIGH);
server.send(200, "text/plain", "LED Encendido");
}
void handleLedOff() {
digitalWrite(ledPin, LOW);
server.send(200, "text/plain", "LED Apagado");
}
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
WiFi.begin(ssid, password);
Serial.print("Conectando a WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Conectado, IP: ");
Serial.println(WiFi.localIP());
// Rutas HTTP
server.on("/", handleRoot);
server.on("/led/on", handleLedOn);
server.on("/led/off", handleLedOff);
server.begin();
Serial.println("Servidor HTTP iniciado");
}
void loop() {
server.handleClient();
}