在局域网下通过IP地址控制ESP32-S3上的LED,可以使用UDP或TCP协议。以下是一个基于UDP协议的完整示例,包括ESP32-S3的服务器代码和一个简单的Python客户端代码。
ESP32-S3 服务器代码
import socket
import time
import network
import machine
led = None
udp_socket = None
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('your_wifi_ssid', 'your_wifi_password') # 替换为你的 Wi-Fi SSID 和密码
i = 1
while not wlan.isconnected() and i <= 10: # 最多尝试10次
print("正在链接...{}".format(i))
i += 1
time.sleep(1)
if not wlan.isconnected():
print("Wi-Fi连接失败,请检查SSID和密码")
return False
print('network config:', wlan.ifconfig())
return True
def start_udp():
global udp_socket
try:
# 创建UDP套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定本地信息
udp_socket.bind(("0.0.0.0", 7788)) # 使用0.0.0.0绑定所有可用接口
udp_socket.settimeout(100) # 设置超时时间为5秒
print("UDP服务器已启动,等待连接...")
return True
except Exception as e:
print("启动UDP服务器失败:", e)
return False
def main():
global led, udp_socket
# 1. 连接Wi-Fi
if not do_connect():
print("Wi-Fi连接失败,程序退出")
return
# 2. 创建灯对象
led = machine.Pin(3, machine.Pin.OUT)
led.value(0) # 初始状态为关闭
# 3. 启动UDP
if not start_udp():
print("UDP服务器启动失败,程序退出")
return
try:
while True:
try:
# 接收网络数据
recv_data, sender_info = udp_socket.recvfrom(1024)
print("{} 发送: {}".format(sender_info, recv_data))
recv_data_str = recv_data.decode("utf-8")
print("接收到的数据:", recv_data_str)
# 处理接收的数据
if recv_data_str == "light on":
print("打开灯...")
led.value(1)
elif recv_data_str == "light off":
print("关闭灯...")
led.value(0)
else:
print("未知命令:", recv_data_str)
except Exception as e:
print("处理数据时出错:", e)
except KeyboardInterrupt:
print("程序被用户中断")
finally:
# 关闭UDP套接字
if udp_socket:
udp_socket.close()
print("UDP服务器已关闭")
if __name__ == "__main__":
main()
Python 客户端代码
使用Python客户端向ESP32-S3发送控制指令:
import socket
# ESP32-S3的IP地址和端口
ESP32_IP = "192.168.1.37" # 替换为你的ESP32-S3的IP地址
UDP_PORT = 7788
# 创建UDP socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def send_command(command):
udp_socket.sendto(command.encode('utf-8'), (ESP32_IP, UDP_PORT))
print(f"已发送命令: {command}")
# 示例:发送控制指令
try:
while True:
command = input("输入命令 (light on/light off/exit): ")
if command == "exit":
break
send_command(command)
except KeyboardInterrupt:
print("程序被用户中断")
finally:
udp_socket.close()
print("UDP客户端已关闭")
或者使用网络调试助手:
使用说明
-
ESP32-S3代码:
- 将代码上传到ESP32-S3。
- 确保Wi-Fi SSID和密码正确。
- 确保LED引脚配置正确。
-
Python客户端:
- 替换
ESP32_IP
为ESP32-S3的IP地址。 - 运行客户端代码,输入
light on
或light off
来控制LED。
- 替换
-
运行:
- 先运行ESP32-S3的代码,确保其连接到Wi-Fi并启动UDP服务器。
- 运行Python客户端,发送控制指令。
通过以上步骤,你可以在局域网下通过IP地址控制ESP32-S3上的LED的亮灭。