在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()
浏覽器位址換成你自己的,如下圖:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHL90TQOhXQq10cWdlYo5kMMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLzUTOwMTOzEDMzEDNwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)