serveur-web.ino

ESP8266 (ESP-12E module) · File : serveur-web.ino · Language : Arduino · Use case : Serveur web embarqué pour piloter une sortie

The sketch that turns the NodeMCU into an IoT gadget: a locally served HTML page, links driving the LED, remote reboot. No infrastructure — it all fits in the 4 MB of flash.

Hardware required

An ESP-12E module (ESP8266EX, 2.4 GHz Wi-Fi) mounted on a NodeMCU / Wemos D1 mini board, powered over micro-USB. A 2.4 GHz Wi-Fi access point (the 8266 cannot see 5 GHz).

Wiring

No mandatory wiring; LED on D4. Micro-USB power suffices (Wi-Fi draws ~200 mA peaks).

How it works

ESP8266WebServer registers lambda routes; handleClient() serves requests at loop() pace. ESP.restart() reboots cleanly, handy when the module trips its watchdog. In the Arduino IDE, install the « esp8266 » package, select « NodeMCU 1.0 (ESP-12E Module) » then Upload (hold GPIO0 LOW if flashing fails). The A0 ADC reads 0-1 V (NodeMCU divider: 0-3.3 V).

Going further

Add the previous sketch's DHT11 to the page, or switch to access-point mode for router-free use.

serveur-web.ino

// Serveur web ESP8266 : page de controle LED D4 + bouton reboot.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char *SSID = "votre-wifi";
const char *CLE = "votre-cle";
const int LED = 2;

ESP8266WebServer serveur(80);

void page() {
  String h = "<h1>ESP8266</h1>"
    "<p>LED : " + String(digitalRead(LED) == LOW ? "ALLUMEE" : "eteinte") + "</p>"
    "<p><a href=/on>ALLUMER</a> | <a href=/off>ETEINDRE</a> | "
    "<a href=/reboot>reboot</a></p>";
  serveur.send(200, "text/html", h);
}

void setup() {
  pinMode(LED, OUTPUT); digitalWrite(LED, HIGH);  // LED eteinte (actif-bas)
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, CLE);
  while (WiFi.status() != WL_CONNECTED) { delay(300); Serial.print("."); }
  Serial.printf("\nhttp://%s/\n", WiFi.localIP().toString().c_str());

  serveur.on("/", page);
  serveur.on("/on", []()  { digitalWrite(LED, LOW);  page(); });
  serveur.on("/off", []() { digitalWrite(LED, HIGH); page(); });
  serveur.on("/reboot", []() { serveur.send(200, "text/plain", "bye");
                               ESP.restart(); });
  serveur.begin();
}

void loop() { serveur.handleClient(); }

← Back to the board