ESP8266 ESP32 MiroPython 连接wifi示例代码
自定义wifi连接类 wifi.py
import network import time class WIFIClient: def __init__(self, ssid=None, password=None): self.ssid = ssid self.password = password def do_connect(self): if self.ssid is None or self.password is None: print('Wifi 账号或密码错误') else: print('WIFI 开始连接') wlan = network.WLAN(network.STA_IF) wlan.active(True) # 设置最大重试次数 max_retries = 5 retries = 0 while not wlan.isconnected() and retries < max_retries: print('正在尝试连接到网络...') wlan.connect(self.ssid, self.password) # 等待一段时间让连接建立 time.sleep(1) # 等待1秒 retries += 1 if wlan.isconnected(): print('WIFI 连接成功:', wlan.ifconfig()) else: print('连接到网络失败') # 示例使用 # wifi_client = WIFIClient(ssid='your_ssid', password='your_password') # wifi_client.do_connect()
调用示例:test.py
from wifi import WIFIClient def main(): wifi_client = WIFIClient(ssid='wanzi', password='*****') wifi_client.do_connect() main()