前面用webSocket控制灯,今天用tcp建立server来接收大DAYU200发送的TCP命令来控制LED灯的开关:
1、DAYU200的开发详见:【新提醒】【润和软件DAYU200开发板体验】TCP控制Hi3861 - OpenHarmony论坛 - 电子威廉希尔官方网站
论坛 - 广受欢迎的专业电子论坛! (elecfans.com)
2、Banana PI开发,用micropython建立tcpserver。接收到数据后判断命令是否为开关三色灯,然后做出相应的动作:
if data == 'LEDON':
np[0] = (25,25,25) #三色相同即亮白光
np.write() #输出显示
elif data == 'LEDOFF':
np[0] = (0,0,0) #关灯
np.write() #输出显示
整体代码如下:
import network
import socket
import time
from machine import Pin
from neopixel import NeoPixel
pin_48 = Pin(48)
np = NeoPixel(pin_48, 1,bpp=3, timing=1)
SSID="SSID"
PASSWORD="pwd"
port=3861
wlan=None
listenSocket=None
def connectWifi(ssid,passwd):
global wlan
wlan=network.WLAN(network.STA_IF)
wlan.active(True)
wlan.disconnect()
wlan.connect(ssid,passwd)
while(wlan.ifconfig()[0]=='0.0.0.0'):
time.sleep(1)
return True
try:
connectWifi(SSID,PASSWORD)
ip=wlan.ifconfig()[0]
listenSocket = socket.socket()
listenSocket.bind((ip,port))
listenSocket.listen(1)
listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print ('tcp waiting...')
while True:
print("accepting.....")
conn,addr = listenSocket.accept()
print(addr,"connected")
while True:
data = conn.recv(1024)
if(len(data) == 0):
print("close socket")
conn.close()
break
print(data)
data = data.decode()
print(type(data))
print(data)
if data == 'LEDON':
np[0] = (25,25,25)
np.write()
elif data == 'LEDOFF':
np[0] = (0,0,0)
np.write()
ret = conn.send(data)
except:
if(listenSocket):
listenSocket.close()
wlan.disconnect()
wlan.active(False)
下载后运行。详见底部视频。
ESP32S3_TCPLED
|