Skip to content

Instantly share code, notes, and snippets.

@neosarchizo
Created November 26, 2022 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neosarchizo/b44569f462438c619a1ba7dbfa3f912b to your computer and use it in GitHub Desktop.
Save neosarchizo/b44569f462438c619a1ba7dbfa3f912b to your computer and use it in GitHub Desktop.
MicroPython - RPi Pico W 비동기 서버로 LED 제어하기
from network import WLAN, STA_IF
from time import sleep
import socket
from machine import Pin
import uasyncio as asyncio
SSID = 'devicemart'
PASSWORD = 'devicemart1'
HTML = '''<!DOCTYPE html>
<html>
<head>
<title>Pico W</title>
</head>
<body>
<h1>Pico W</h1>
<p>%s</p>
</body>
</html>
'''
led = Pin(18, Pin.OUT)
led.value(0)
led_heartbeat = Pin(19, Pin.OUT)
led_heartbeat.value(0)
wlan = WLAN(STA_IF)
async def serve_client(reader, writer):
print('Client connected')
request_line = await reader.readline()
print('Request:', request_line)
while await reader.readline() != b'\r\n':
pass
request = str(request_line)
led_on = request.find('/led/on')
led_off = request.find('/led/off')
print('index of /led/on = ' + str(led_on))
print('index of /led/off = ' + str(led_off))
if led_on == 6:
print('led on!')
led.value(1)
state = 'LED is ON!'
if led_off == 6:
print('led off!')
led.value(0)
state = 'LED is OFF!'
response = HTML % state
writer.write('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n')
writer.write(response)
await writer.drain()
await writer.wait_closed()
print('Client disconnected')
async def main():
print('Connecting to Network...')
wlan.active(True)
wlan.connect(SSID, PASSWORD)
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('waiting for connection...')
sleep(1)
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else: # wlan.status() == 3
print('connected')
status = wlan.ifconfig()
print('ip = ' + status[0])
print('Setting up webserver...')
asyncio.create_task(asyncio.start_server(serve_client, '0.0.0.0', 80))
while True:
led_heartbeat.value(1)
print('heartbeat')
await asyncio.sleep(0.25)
led_heartbeat.value(0)
await asyncio.sleep(5)
try:
asyncio.run(main())
finally:
asyncio.new_event_loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment