🛠 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.

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials