🛠 Serveur web embarqué pour piloter une LED
Objectives
Host an HTTP server directly on the ESP32-S2 using the WebServer library: serve a control page, drive an LED via GET requests, and display the status. The S2 does not have Bluetooth: 2.4 GHz WiFi is the only network channel, which makes this server even more central.
Hardware
- ESP32-S2 board
- 1 LED + 330 Ω resistor on GPIO2
- 2.4 GHz WiFi network (no 5 GHz)
- Computer/smartphone on the same network
Complete code
// 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; }
Expected verification
The console displays the IP assigned by the router (e.g., http://192.168.1.42). From a browser on the same network, the page displays with the current status; the TURN ON button lights the physical LED and updates the page, TURN OFF extinguishes it. Control works from multiple devices simultaneously.
Common errors
- 5 GHz network: The S2's radio is 2.4 GHz only, connection fails in a loop on a 5 GHz SSID.
- Forgetting
serveur.handleClientinloop: the page never responds or freezes the browser. - Using an ADC2 pin for a sensor in the same project: ADC2 is blocked as soon as WiFi is active; stick to ADC1 (GPIO1-14).
- Blocking in
loop(long delays): the server stops responding; keep the loop lightweight or usedelay(1)to yield control.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht22.inoArduinooled-i2c.inoArduinoserveur-web.inoArduino