🛠 Serveur web embarqué pour piloter une LED

ESP32-S2 · avance · Schéma : IMG-esp32-s2-avance-3-esp32-s2-serveur-web-led.svg — ESP32-S2 connectée au WiFi local, LED sur GPIO2 avec résistance de 330 Ω, un ordinateur et un smartphone affichent la page web servie par la carte avec boutons ON/OFF.

Objetivos

Alojar un servidor HTTP directamente en el ESP32-S2 con la biblioteca WebServer: servir una página de control, controlar un LED mediante peticiones GET y mostrar el estado. El S2 no dispone de Bluetooth: la WiFi de 2,4 GHz es el único canal de red, lo que hace que este servidor sea aún más central.

Material

Código completo

// Serveur web de pilotage LED sur ESP32-S2
#include <WiFi.h>
#include <WebServer.h>

const char *SSID = "VOTRE_WIFI";
const char *PASS = "VOTRE_MOT_DE_PASSE";
const uint8_t LED_PIN = 2;
bool etatLed = false;
WebServer serveur(80);

const char *PAGE =
  "<!doctype html><html lang='fr'><head><meta charset='utf-8'>"
  "<meta name='viewport' content='width=device-width,initial-scale=1'>"
  "<title>ESP32-S2</title></head><body style='font-family:sans-serif;"
  "text-align:center;padding-top:40px'>"
  "<h1>LED ESP32-S2</h1><p>Etat : %s</p>"
  "<a href='/on'><button style='font-size:1.4em;padding:10px 24px'>ALLUMER</button></a> "
  "<a href='/off'><button style='font-size:1.4em;padding:10px 24px'>ETEINDRE</button></a>"
  "</body></html>";

void pageAccueil {
  String html; html.reserve(600);
  html.printf(PAGE, etatLed ? "ALLUMEE" : "ETEINTE");
  serveur.send(200, "text/html", html);
}

void setup {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
  WiFi.begin(SSID, PASS);
  Serial.print("Connexion WiFi");
  while (WiFi.status != WL_CONNECTED) { delay(300); Serial.print("."); }
  Serial.printf("\nAdresse : http://%s\n", WiFi.localIP.toString.c_str);
  serveur.on("/", pageAccueil);
  serveur.on("/on", []  { etatLed = true;  digitalWrite(LED_PIN, HIGH); serveur.send(303, "text/plain", "ok"); pageAccueil; });
  serveur.on("/off", [] { etatLed = false; digitalWrite(LED_PIN, LOW);  serveur.send(303, "text/plain", "ok"); pageAccueil; });
  serveur.begin;
}

void loop { serveur.handleClient; }

Verificación esperada

La consola muestra la IP asignada por el router (por ejemplo, http://192.168.1.42). Desde un navegador en la misma red, la página se muestra con el estado actual; el botón ENCENDER enciende el LED físico y actualiza la página, APAGAR lo apaga. El control funciona desde varios dispositivos simultáneamente.

Errores frecuentes

Otros tutoriales para esta placa

Ejemplos de código para esta placa

← Volver a la ficha 🛠 Todos los tutoriales