Chapter 5. 실전 IoT: 웹 기반 원격 LED 제어
우리의 최종 목표입니다. 보드가 서버가 되어, 전 세계 어디서든(같은 와이파이 내) 스마트폰으로 LED를 켜고 끌 수 있게 만듭니다.
스마트폰 웹 브라우저를 통해 원격으로 보드 제어하기
5.1 전체 프로젝트 코드
아래 코드를 main.py로 저장하여 실행하세요.
import network
import socket
import time
from machine import Pin
# 네트워크 설정 (본인 정보 기입)
ssid = '와이파이_이름'
password = '비밀번호'
led = Pin("LED", Pin.OUT)
# Wi-Fi 연결 함수
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
time.sleep(1)
ip = wlan.ifconfig()[0]
print(f'서버 가동! 접속 주소: http://{ip}')
# 웹 서버 대기 (Socket)
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
# 웹사이트 화면 구성
def get_html():
return """<!DOCTYPE html>
<html>
<body style="text-align:center;">
<h1>Pico 2 W 원격 제어</h1>
<a href="/?led=on"><button style="font-size:30px; background:green; color:white;">LED ON</button></a>
<a href="/?led=off"><button style="font-size:30px; background:red; color:white;">LED OFF</button></a>
</body>
</html>"""
while True:
try:
cl, addr = s.accept()
request = cl.recv(1024).decode('utf-8')
if '/?led=on' in request: led.value(1)
if '/?led=off' in request: led.value(0)
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
cl.send(get_html())
cl.close()
except Exception as e:
cl.close()
5.2 실습 마무리
- 코드를 실행하고 출력된
http://192.168.x.x주소를 확인합니다. - 같은 와이파이에 연결된 스마트폰 브라우저에 이 주소를 입력합니다.
- 화면에 뜬 LED ON/OFF 버튼을 눌러보세요!
🎉 축하합니다!
이제 당신은 보이지 않는 전파를 통해 물리적인 하드웨어를 제어하는 진정한 IoT 메이커가 되었습니다.