参考王铭东 老师的教程
https://www.itprojects.cn/coursecenter-hardware.html
软件+硬件 @ MicroPython+ESP32相关@课件@五、PC远程控制ESP32 LED灯
增加功能: 接收到无效指令,返回提示信息
# 整体流程 # 1. 链接wifi # 2. 启动网络功能(UDP) # 3. 接收网络数据 # 4. 处理接收的数据import socket import time import network import machinedef do_connect():wlan = network.WLAN(network.STA_IF)wlan.active(True)if not wlan.isconnected():print('connecting to network...')wlan.connect('dongfeiqiu', 'wangmingdong1225')# 输入wifi热点账号和密码i = 1while not wlan.isconnected():print("正在链接...{}".format(i))i += 1time.sleep(1)print('network config:', wlan.ifconfig())def start_udp():# 2. 启动网络功能(UDP)# 2.1. 创建udp套接字udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)# 2.2. 绑定本地信息udp_socket.bind(("0.0.0.0", 7788))return udp_socketdef main():# 1. 链接wifi do_connect()# 2. 创建UDPudp_socket = start_udp()# 3. 接收网络数据while True:recv_data, sender_info = udp_socket.recvfrom(1024)print("{}发送{}".format(sender_info, recv_data))try:# 错误信息处理recv_data_str = recv_data.decode("utf-8")print(recv_data_str)except Exception as ret:print("error:", ret)continue# 4. 处理接收的数据if recv_data_str == "light on":print("这里是要灯亮的代码...")#led.value(1)elif recv_data_str == "light off":print("这里是要灯灭的代码...")#led.value(0)else: #返回错误提示msg ="please input light on or light off"# 输入对方的ip地址dest_ip = sender_info[0]# 输入对方的portdest_port = int(sender_info[1])# 发送数据udp_socket.sendto(msg.encode("utf-8"), (dest_ip, dest_port))if __name__ == "__main__":main()