Skip to content

Instantly share code, notes, and snippets.

@theskanthunt42
Last active April 13, 2024 06:50
Show Gist options
  • Save theskanthunt42/bf689a9fc20fc1768393dba6c73a7428 to your computer and use it in GitHub Desktop.
Save theskanthunt42/bf689a9fc20fc1768393dba6c73a7428 to your computer and use it in GitHub Desktop.
Simple HTTP server running on MicroPython
<html>
<h1>MicroPython HTTP Server on Raspberry Pi Pico W</h1>
Your IP address is: %s:%d
<br>
</html>
#AP mode test
#U could really tell how all this begin...
import network
import socket
import time
import gc
import machine
import _thread
ssid = ''
pwd = ''
port = 80
html_path = 'index.html'
led = machine.Pin("LED", machine.Pin.OUT)
gc.enable()
#NetworkBlink(35, 3) 35ms fits the bill just right
def NetworkBlink(delay:int , interval: int):
for tmp in range(interval):
led.value(0)
time.sleep_ms(delay)
led.value(1)
time.sleep_ms(delay)
return True
def ReadHTML(path: str) -> str:
with open(f"{path}", "r") as f:
html = str(f.read())
return html
def main():
machine.freq(240000000)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
print("Boot delay for Wi-Fi module...")
time.sleep(1)
wlan.connect(ssid, pwd)
if wlan.active():
pass
else:
wlan.active(True)
retry_count = 10
while retry_count > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
retry_count -= 1
print('Connecting to Wi-Fi...')
time.sleep(1)
if wlan.status() != 3:
raise RuntimeError('Network connection failed')
else:
print(f"Connected to: {ssid}\nIP address: {wlan.ifconfig()[0]}")
led.value(1)
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((wlan.ifconfig()[0], port))
s.listen(4)
while True:
try:
print("Now waiting for connection...")
client, address = s.accept()
NetworkBlink(35, 2)
print(f"Incoming connection from: {address}\n")
incoming_data = client.recv(1024)
print(f"Header/Data from {address}: \n{incoming_data}\n")
data = ReadHTML(html_path)
rsp = data % (address[0], address[1]) #backend stuff
client.send("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n")
client.send(rsp)
print("Data sent.")
NetworkBlink(35, 3)
#client.close()
gc.collect()
except OSError as error:
client.close()
print(f"Lost connection to client due to:\n{error}")
break
except KeyboardInterrupt:
client.close()
print("Interruptted by user.")
led.value(0)
break
finally:
client.close()
print("Connection is closed")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment