最近入手了TPYBoard v202:
下面用的是micropython開發的led例程,板子連接wifi後獲取到Ip地址,並打印在串口上,通過ip地址用浏覽器訪問頁面,實現控制led開關:
效果:
我在官方的例程做了稍稍改動,去除了登錄頁面,美化了一下控制頁面:
由於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;'>💡</span>
<p>燈光: </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] #連接的客戶端
led_flag.value(1) #設置8266 led常亮
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()
myip=do_connect('essid','password')#家中網絡的WIFI名稱和密碼
print(myip)
main(myip)
server.zip
python還是適用於樹莓派之類的性能高的比較合適,不太適用於MCU,雖然MicroPython比Arduino強大一些,但是運行性能不及Arduino