自己建立一个web server,就是自己建立一个网站服务器,就会有一个ip地址,在手机或电脑和esp32连接同一个wifi的情况下,让手机或电脑登录那个ip地址的网站就可以给esp32发送相应信息,esp32收到不同的信息执行不同操作,本代码就是实现控制开灯与关灯。
from machine import Pin
import network
import socket
led = Pin(2,Pin.OUT)
ssid = 'Mi10s' #wifi名称
password = 'jjh18776489677' #wifi密码
def wifi_connect():
wlan=network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("connecting to network ......")
wlan.connect(ssid,password)
while not wlan.isconnected():
led.value(1)
time.sleep_ms(250)
led.value(0)
time.sleep_ms(250)
led.value(0)
return False
else:
led.value(0)
print("network information:",wlan.ifconfig())
return True
def web_page():
html = """<html><head><meta name="viewport"
content="width=device-width, initial-scale=1"></head>
<body><h1>Ojay Server</h1><a
href=\"?led=on\"><button>ON</button></a>
<a
href=\"?led=off\"><button>OFF</button></a></body><html>"""
return html
if __name__=="__main__":
if wifi_connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('',80))
s.listen(5)
while True:
client, addr = s.accept()
print('Got a connection from %s' % str(addr))
request = conn.recv(1024)
request = str(request)
print('Content = %s' % request)
led_on = request.find('/?led=on')#接收到对象在第几个位置出现,返回出现的第几个位置
led_off = request.find('/?led=off')
if led_on == 6:#第六个位置接收到, href=\"?led=on\"(在第六个字符)
print('LED ON')
led.value(1)
if led_off == 6:
print('LED OFF')
led.value(0)
response = web_page()
conn.send('HTTP/1.1 200 OK\n')
conn.send('Content-Type: text/html\n')
conn.send('Connection: close\n\n')
conn.send('HTTP/1.1 200 OK\n')
conn.sendall(response)
conn.close()
if led_on == 6:##接收到的在第六个位置
在返回的IP地址,复制在网页中打开即可,如192.168.191.5
参考https://blog.csdn.net/weixin_45116099/article/details/119191907