Created
November 25, 2022 03:59
-
-
Save neosarchizo/ea79fe05dc7c03024260515dc4ce94cf to your computer and use it in GitHub Desktop.
MicroPython - RPi Pico W 서버로 LED 제어하기
This file contains 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
from network import WLAN, STA_IF | |
from time import sleep | |
import socket | |
from machine import Pin | |
led = Pin(18, Pin.OUT) | |
led.value(0) | |
SSID = 'devicemart' | |
PASSWORD = 'devicemart1' | |
HTML = '''<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Pico W</title> | |
</head> | |
<body> | |
<h1>Pico W</h1> | |
<p>%s</p> | |
</body> | |
</html> | |
''' | |
wlan = WLAN(STA_IF) | |
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]) | |
addr_server = socket.getaddrinfo('0.0.0.0', 80)[0][-1] | |
s = socket.socket() | |
s.bind(addr_server) | |
s.listen(1) | |
print('Listening on', addr_server) | |
state = '' | |
while True: | |
try: | |
cl, addr_client = s.accept() | |
print('client connected from', addr_client) | |
request = cl.recv(1024) | |
print(request) | |
request = str(request) | |
led_on = request.find('/led/on') | |
led_off = request.find('/led/off') | |
print( 'led on = ' + str(led_on)) | |
print( '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 | |
cl.send('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n') | |
cl.send(response) | |
cl.close() | |
except OSError as e: | |
cl.close() | |
print('connection closed') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment