MicroPython Server网页LED开关

Title
MicroPython Server网页LED开关
Date
May 14, 2023
最近入手了TPYBoard v202:
notion image
下面用的是micropython开发的led例程,板子连接wifi后获取到Ip地址,并打印在串口上,通过ip地址用浏览器访问页面,实现控制led开关:
效果:
notion image
我在官方的例程做了稍稍改动,去除了登录页面,美化了一下控制页面:
由于esp8266自带内存太小,一次性打开的device.html不可以太大,否则会出现网页文件不全,在手机端无法显示网页,所以一定要注意这个。
device.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <style> body{width: 100%;height: 100vh;display: flex;justify-content: center;align-items: center;background-color: #efeeee; } input[type="submit"] { background-color: #F5F5F5;border: 20px solid rgba(0, 0, 0, 0.1);color: #666666;font-size: 20px;font-weight: bold; height: 100px; line-height: 27px; margin: 11px 6px; min-width: 100px; padding: 0 8px;text-align: center; } </style> <title>智能家居平台</title> </head> <body> <div class="container"> <center> <h2>智能家居控制平台</h2> <form action="/" method="get" accept-charset="utf-8"> <span style='font-size:100px;'>&#128161;</span> <p>灯光:&nbsp;</p> <input type="Submit" value="ON" name="led" /> <input type="Submit" value="OFF" name="led" /> </form> </center> </div> </body> </html>
main.py
try: import usocket as socket except: import socket import network from machine import UART from machine import Pin led_flag=Pin(2, Pin.OUT) led = Pin(4, Pin.OUT) //继电器开关控制针脚连接G4针脚 led.value(0) led_flag.value(0) def do_connect(ssid,pwd): sta_if = network.WLAN(network.STA_IF)#STA 模式 sta_if.active(False) if not sta_if.isconnected():#判断是否连接 sta_if.active(True) sta_if.connect(ssid,pwd)#ssid:WIFI名称 pwd:WIFI 密码 while not sta_if.isconnected(): pass if sta_if.isconnected(): return sta_if.ifconfig()[0] def main(ip_): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ai = socket.getaddrinfo(ip_, 80) addr = ai[0][-1] s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) s.bind(addr) s.listen(5) led_flag.value(0) while True: res = s.accept() client_s = res[0] #连接的客户端 # client_addr = res[1] led_flag.value(1) #设置8266 led常亮 # req = client_s.readline() req = client_s.recv(1024).decode('utf-8') print(req) try: req_path = req.split(" ")[1] except: continue print("req_path:------",req_path) if req_path.find('favicon.ico') > -1: client_s.send(" ") client_s.close() continue elif req_path.find('led=ON') > -1: led.value(1) print('led:', led.value()) led_flag.value(0) elif req_path.find('led=OFF') > -1: led.value(0) print('led:', led.value()) led_flag.value(0) elif req_path.find('ledstatus') > -1: client_s.send(str(led.value())) client_s.close() continue with open('device.html','r') as f: client_s.send(f.read()) client_s.close() # client_s.send(dev_data) # client_s.close() myip=do_connect('essid','password')#家中网络的WIFI名称和密码 print(myip) main(myip)
notion image
python还是适用于树莓派之类的性能高的比较合适,不太适用于MCU,虽然MicroPython比Arduino强大一些,但是运行性能不及Arduino
Built with Potion.so