在ESP8266 NodeMcu V3中使用MicroPython编写一个HTTP Web服务器
本文介绍了在ESP8266 NodeMcu V3中如何使用MicroPython通过socket编程建立一个HttpWeb服务器。服务器运行后可通过浏览器访问控制ESP8266 NodeMcu V3板载LED开关。
成果:使连接的LED可以从浏览器客户端打开或关闭。
方法:创建套接字并监听套接字。
import machine
import socket
import time
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect('用户名', '密码')
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
html='''<!DOCTYPE html>
<html>
<head><meta charset='UTF-8'><title>网络led开关服务器</title></head>
<center><h2>网络LED开关服务器</h2></center>
<center><form>
<button name="LED" value='ON' type='submit'> LED ON </button>
<button name="LED" value='OFF' type='submit'> LED OFF </button>
</form>
</center>
'''
LED0 = machine.Pin(2,machine.Pin.OUT)
#led off
LED0.value(1)
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)
print("Content %s" % str(request))
request=str(request)
LEDON=request.find('/?LED=ON')
LEDOFF=request.find('/?LED=OFF')
if(LEDON==6):
LED0.value(0)
if(LEDOFF==6):
LED0.value(1)
response=html
conn.send(response)
conn.close()
浏览器地址换成你自己的,如下图: