🛠 Serveur web de commande d'une LED en MicroPython

ESP8266 (ESP-12E module) · intermediaire · Schéma : IMG-esp8266-esp-12e-intermediaire-2-esp8266-serveur-web-led.svg — Module ESP-12E exécutant MicroPython, LED embarquée sur GPIO2 (active-LOW), connecté au réseau local, navigateur d'un ordinateur ou smartphone sur le même réseau.

Objectives

Run a mini HTTP server on the ESP8266 with MicroPython, without any external libraries: we directly use the socket module to accept TCP connections on port 80, parse the request line, and return an HTML page with two links that turn the onboard LED GPIO2 on and off. This tutorial shows another way to program the chip (the MicroPython esp8266 port is very lightweight), the active-LOW principle of the GPIO2 LED (value 0 = on), and retrieving the IP via ifconfig. To be done from a computer on the same network as the module.

Hardware

Complete code

# main.py MicroPython (port esp8266) - serveur LED sur GPIO2
import network
import socket

led = network and __import__("machine").Pin(2, 1)  # GPIO2 en sortie

sta = network.WLAN(network.STA_IF)
sta.active(True)
if not sta.isconnected:
    sta.connect("mon-reseau", "mot-de-passe")
    import time
    for _ in range(40):
        if sta.isconnected:
            break
        time.sleep_ms(250)
print("IP =", sta.ifconfig[0])

html = ("<h1>ESP-12E</h1>"
        "<a href='/on'><button>ALLUMER</button></a> "
        "<a href='/off'><button>ETEINDRE</button></a>")

def handle(req):
    if req.startswith("GET /on"):        # LED active-LOW : 0 = allumee
        led.value(0)
    elif req.startswith("GET /off"):
        led.value(1)
    return html

s = socket.socket
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0", 80))
s.listen(1)
while True:
    cl, _ = s.accept
    req = cl.recv(100).decode
    cl.send("HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n" + handle(req))
    cl.close

Note: the pin initialization line can also be written cleanly as import machine; led = machine.Pin(2, machine.Pin.OUT) if you paste the code into a real main.py file.

Expected verification

After startup, the console displays the module's IP (for example 192.168.1.57). Open this address in a browser on the same network: the page with two buttons appears. "TURN ON" sets the GPIO2 pin to off (value 0) and turns on the onboard LED; "TURN OFF" does the opposite. The module must remain responsive after several clicks.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials