Skip to content

Instantly share code, notes, and snippets.

@neosarchizo
Created November 24, 2022 04:45
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/c73e14648c3cc4fc660bea1a18471e50 to your computer and use it in GitHub Desktop.
Save neosarchizo/c73e14648c3cc4fc660bea1a18471e50 to your computer and use it in GitHub Desktop.
MicroPython - RPi Pico W 서버 실행하기
from network import WLAN, STA_IF
from time import sleep
import socket
SSID = 'devicemart'
PASSWORD = 'devicemart1'
HTML = '''<!DOCTYPE html>
<html>
<head>
<title>Pico W</title>
</head>
<body>
<h1>Pico W</h1>
<p>Hello DeviceMart!!</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)
while True:
try:
cl, addr_client = s.accept()
print('client connected from', addr_client)
cl_file = cl.makefile('rwb', 0)
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
response = HTML
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