Last active
January 4, 2023 21:06
-
-
Save yarons/1927f990b6aa08b87c877b55cb31aff5 to your computer and use it in GitHub Desktop.
Micropython on ESP32 running a Webserver that blinks the LED according to a parameter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# First replace SSID and PASS with yor Wi-Fi's SSID and password. | |
# The IP for the Webserver will appear in the console. | |
# In order to make the LED blink type the following | |
# in your Web Browser or curl: | |
# http://<esp32_ip>/blink=<amount> | |
# For example: | |
# http://192.168.1.50/blink=4 | |
import socket | |
from machine import Pin | |
from time import sleep_ms | |
import re | |
led = Pin(2, Pin.OUT) | |
HOST = "0.0.0.0" # Standard loopback interface address (localhost) | |
PORT = 80 # Port to listen on (non-privileged ports are > 1023) | |
SSID = 'YOUR_WIFI_SSID' | |
PASS = 'YOUR_WIFI_PASS' | |
def do_connect(): | |
import network | |
wlan = network.WLAN(network.STA_IF) | |
wlan.active(True) | |
if not wlan.isconnected(): | |
print('connecting to network...') | |
wlan.connect(SSID, PASS) | |
while not wlan.isconnected(): | |
pass | |
print('network config:', wlan.ifconfig()) | |
def blink_led(num): | |
for i in range(num*2): | |
led.value(not led.value()) | |
sleep_ms(500) | |
led.value(0) | |
def http_server(): | |
html = """<!DOCTYPE html> | |
<html> | |
<head> <title>ESP32 Server</title> </head> | |
<body> | |
<h1>Welcome to ESP32 Server, the LED will blink if the correct parameter specified</h1> | |
</body> | |
</html> | |
""" | |
addr = socket.getaddrinfo(HOST, PORT)[0][-1] | |
s = socket.socket() | |
s.bind(addr) | |
s.listen(1) | |
print('listening on', addr) | |
while True: | |
cl, addr = s.accept() | |
print('client connected from', addr) | |
cl_file = cl.makefile('rwb', 0) | |
while True: | |
line = cl_file.readline() | |
r1 = re.match('GET',line) | |
if r1: | |
param = line.decode().split()[1].replace('?','=').split('=')[1] | |
if param == 'blink': | |
blink_num = int(line.decode().split()[1].replace('?','=').split('=')[2]) | |
if not line or line == b'\r\n': | |
break | |
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n') | |
cl.send(html) | |
try: | |
blink_num | |
blink_led(blink_num) | |
except NameError: | |
blink_num = None | |
cl.close() | |
do_connect() | |
http_server() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment