功夫不负有心人,经过多日苦心摸索,终于攻克网页端控制LED的亮灭。
首先编写以下代码:
from machine import Pin
import network
import socket
import time
led = Pin(2,Pin.OUT)
ssid = "iPhone (50)"
password = "qq7895123"
def wifi_connect():
global wlan
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="""
content="width=device-width,initial-scale=1">
0jay Server
href= "?led=on\">
href=\"?led=off\">"""
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:
conn,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:
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()
然后,下载到ESP32中运行。
最后,打开网页,即可控制LED的亮灭。