掌控板micropython编程网页端控制灯带LED的亮灭
一、使用扩展板连接7个LED的灯带
Mind+趣味学习套件中有一条7个LED的灯带。将灯带连接到扩展板的P13引脚上,在掌控板的原理图上,P13对应的GPIO是18。在编程中使用Pin(18)对彩带进行初始化。
设置彩带颜色的代码如下:
from machine import Pin
import neopixel
# 配置 NeoPixel 灯带,使用 GPIO18,灯带有 3 LED
np = neopixel.NeoPixel(Pin(18), 7)
np[0] = (255, 0, 0)
np[1] = (0,255, 0)
np[2] = (0,255, 0)
np.write()
则前三个LED显示的颜色分别是红色、绿色和绿色。
二、掌控板板载灯带的初始化
掌控板上使用的三颗LED是灯带的LED,原理图如图所示。
NeoPixel 灯带使用 GPIO17接口,灯带有 3 LED,因此使用np = neopixel.NeoPixel(Pin(17), 3)进行初始化。
from machine import Pin
import neopixel
# 配置 NeoPixel 灯带,使用 GPIO17,灯带有 3 LED
np = neopixel.NeoPixel(Pin(17), 3)
np[0] = (255, 0, 0)
np[1] = (0,255, 0)
np[2] = (0,0, 255)
np.write()
三、掌控板中使用micropython编程实现了在网页端控制灯带LED的亮灭
代码如下:
import network
import socket
from machine import Pin
import neopixel
# 配置 NeoPixel 灯带,使用 GPIO17,灯带有 3 LED
np = neopixel.NeoPixel(Pin(17), 3)
# 设置你的SSID和密码
ssid = 'TP-LINK_FF40'
password = 'synu0268'
# 连接到WiFi
def connect_to_wifi():
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():
pass
print('Network config:', wlan.ifconfig())
# 创建Web页面
def web_page():
html = """
<html>
<head>
<title>ESP32 NeoPixel Control</title>
</head>
<body>
<h1>ESP32 NeoPixel Control</h1>
<p><a href="/?NeoPixel0=on"><button>NeoPixel0 ON</button></a></p>
<p><a href="/?NeoPixel1=on"><button>NeoPixel1 ON</button></a></p>
</body>
</html>
"""
return html
# 启动Web服务器
def start_server():
connect_to_wifi()
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)
NeoPixel0_on = request.find('/?NeoPixel0=on')
NeoPixel1_on = request.find('/?NeoPixel1=on')
if NeoPixel0_on == 6:
print('NeoPixel0 on')
np[0] = (255, 0, 0)
np[1] = (0, 0, 0)
# 更新显示
np.write()
if NeoPixel1_on == 6:
print('NeoPixel1 on')
np[1] = (0, 255, 0)
np[0] = (0, 0, 0)
# 更新显示
np.write()
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.sendall(response)
conn.close()
start_server()
在Thonny中运行程序,在shell中显示如下
在浏览器中输入192.168.1.102,显示如下,点击按钮“NeoPixel0 ON”则可控制灯带上的第一个LED发红色的光,点击按钮“NeoPixel1 ON”则第一个LED等灭,第二个led灯显示绿色。