capteur_web.py

ESP8266 (ESP-12E module) · File : capteur_web.py · Language : MicroPython · Use case : Servir des mesures en MicroPython pur sur l'ESP8266

MicroPython on ESP8266 means Wi-Fi in a scripting language: this DHT logger fits in 40 lines with zero compilation. The socket module serves raw HTML — enough for a home-made dashboard.

Hardware required

An ESP-12E module (ESP8266EX, 2.4 GHz Wi-Fi) mounted on a NodeMCU / Wemos D1 mini board, powered over micro-USB. 1 DHT11 on GPIO4 (DATA + 10 kΩ pull-up, VDD 3.3 V, GND).

Wiring

Same wiring as the DHT sketch: DATA on pin 4 (D2). Power over USB; Wi-Fi draws the current peaks.

How it works

network.WLAN joins the AP, socket bind/listen/accept makes a minimal HTTP server: each request triggers a measurement and returns a page. The try/except absorbs dropped connections. 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 an /api path in JSON for a real dashboard, or enable WebREPL to debug over Wi-Fi.

capteur_web.py

# MicroPython ESP8266 : DHT sur GPIO4 + mini serveur HTTP + WebREPL.
# Copier en main.py. WebREPL : https://werelup.pythonanywhere.com (optionnel).
import network, dht, machine, socket, time

sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect("votre-wifi", "votre-cle")
for _ in range(40):
    if sta.isconnected():
        break
    time.sleep_ms(250)
print("IP:", sta.ifconfig()[0])

dht11 = dht.DHT11(machine.Pin(4))
led = machine.Pin(2, machine.Pin.OUT)

addr = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
addr.bind(("", 80))
addr.listen(2)
print("Serveur HTTP sur le port 80")

while True:
    client, _ = addr.accept()
    try:
        client.recv(200)                       # on lit la requete, on l'oublie
        dht11.measure()
        html = ("<h1>T=%.0f C  HR=%.0f %%</h1>" %
                (dht11.temperature(), dht11.humidity()))
        reponse = ("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n"
                   "Content-Length: %d\r\n\r\n%s" % (len(html), html))
        client.send(reponse)
        led.value(not led.value())
    except OSError:
        pass
    finally:
        client.close()

← Back to the board