在使用ESP32连接热点前,需要先使用手机或者电脑打开一个热点,并设置为2.4频段G的,如下图所示。
ESP32连接wifi热点官方示例
import networkwlan = network.WLAN() # create station interface (the default, see below for an access point interface)
wlan.active(True) # activate the interface
wlan.scan() # scan for access points
wlan.isconnected() # check if the station is connected to an AP
wlan.connect('ssid', 'key') # connect to an AP
wlan.config('mac') # get the interface's MAC address
wlan.ipconfig('addr4') # get the interface's IPv4 addressesap = network.WLAN(network.WLAN.IF_AP) # create access-point interface
ap.config(ssid='ESP-AP') # set the SSID of the access point
ap.config(max_clients=10) # set how many clients can connect to the network
ap.active(True) # activate the interface
官方文档地址:https://docs.micropython.org/en/latest/esp32/quickref.html#networking
编写MicroPython 代码测试连接wifi并发送一个消息
import socket
import network
import time# 连接到Wi-Fi网络
def connect_wifi(ssid, password):wlan = network.WLAN(network.STA_IF)wlan.active(True)if not wlan.isconnected():wlan.connect(ssid, password)while not wlan.isconnected():time.sleep(1) # 等待连接print("Wi-Fi连接成功")# 发送UDP消息
def send_udp_message(udp_socket, dest_ip, dest_port, message):udp_socket.sendto(message.encode('utf-8'), (dest_ip, dest_port))print(f"消息 '{message}' 已发送到 {dest_ip}:{dest_port}")# 主程序
if __name__ == "__main__":# 配置Wi-Fi和目标地址connect_wifi('pi', '12345678') # 替换Wi-Fi名称和密码dest_ip = '192.168.2.86'dest_port = 8080# 创建UDP套接字udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)send_data = "hello world"send_udp_message(udp_socket, dest_ip, dest_port, send_data)time.sleep(1) # 控制发送间隔# 5. 关闭套接字udp_socket.close()
运行效果图
注意事项:dest_ip 需要替换成自己的手机或者电脑ip地址