micropython驱动esp32用网页控制舵机实现远程开关灯(代码部分)
在给esp烧录好固件之后,分别写入boot.py和main.py以及html.html。
=======================================================
boot.py:
def hotlink(name='wifiname',pd='12345678'):#开发板开热点方式
try:
import network
hot = network.WLAN(network.AP_IF)
hot.active(True)
hot.config(essid=name)
hot.config(authmode=3, password=pd)
except:
print('hotlink has fall')
def do_connect(name,password):#开发板连接路由器方式
import network
wifi = network.WLAN(network.STA_IF)
if not wifi.isconnected():
print('正在连接wifi')
wifi.active(True) #激活WIFI
wifi.connect(name, password)
while not wifi.isconnected():
pass
print('network config:', wifi.ifconfig())
hotlink('esp','12345678')#在这里我们暂时用开发板开热点方式举例
=======================================================
main.py:
from machine import Pin,PWM
import socket
import time
cod=1.6
State = str((cod-1.6)*10) + '度'
a1 = PWM(Pin(15),freq=50)#舵机信号接口(这里接的是开发板GPIO15)
a1.duty(int((1.6)/20*1023))#0.3~2.6(0.6~2.6为0到180度)
#for i in range(27):#测试舵机
# a1.duty(int((0.1*i)/20*1023))
# time.sleep(0.5)
# print(i)
html = open('html.html','r')
html = html.read()
addr = socket.getaddrinfo('192.168.4.1', 80)[0][-1]#板子自己开热点默认ip
#如果用连接热点方式则要用路由器分配的IP地址
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
while(True):
cl, addr = s.accept()
print(addr)
data = cl.recv(100)
if data.decode()[:20].find("+1") != -1:
if(cod<2.5):
cod = cod+0.1
time.sleep(0.1)
a1.duty(int((cod)/20*1023))
time.sleep(0.1)
State = str(int((cod-1.6)*100)) + '度'
elif data.decode()[:20].find("-1") != -1:
if(cod>=0.4):
cod = cod-0.1
time.sleep(0.1)
a1.duty(int((cod)/20*1023))
time.sleep(0.1)
State = str(int((cod-1.6)*100)) + '度'
print(cod)
response = html % State
cl.send(response)
time.sleep(0.1)
cl.close()
=======================================================
html.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>舵机控制器</title>
</head>
<body>
<font size="100">当前状态 : %s </font>
<br><br>
<a href=\"/+1\"\"> <button style="height:200px;width:300px;background:pink;"> <font size="100">加10度<font></button></a>
<a href=\"/-1\"\"><button style="height:200px;width:300px;background:white;" > <font size="100">减10度<font></button></a><br />
</body>
</html>
=======================================================
请参考:https://www.bilibili.com/video/BV1PT411c711?spm_id_from=333.999.0.0