在CircuitPython中无法为Raspberry Pi Pico W设置软接入点
问题:Raspberry Pi Pico W 用CircuitPython搭建带Web服务器的软AP失败
需要在Raspberry Pi Pico W上搭建无互联网连接的软接入点(热点),并附带Web服务器,用于外出无WiFi场景。必须使用CircuitPython,但遇到以下问题:
- 无法导入
network模块,试过多个版本的CircuitPython固件(包括最新的8.0.3)均无效 - 能导入
wifi模块,但不知道如何用它创建软AP
之前在MicroPython中该功能可正常运行,使用的代码如下:
import network ap_ssid = "myAP" ap_password = "password123" # create access point interface ap_if = network.WLAN(network.AP_IF) # disable default access point ap_if.active(False) # configure access point settings ap_if.active(True) ap_if.config(essid=ap_ssid, password=ap_password) # print access point settings print("Access point created with SSID: {}, password: {}".format(ap_ssid, ap_password)) print("Access point IP address:", ap_if.ifconfig()[0])
解决方法
CircuitPython和MicroPython的WiFi API完全不同,没有network模块,需要用wifi、socketpool和adafruit_httpserver库来实现软AP+Web服务器的功能,步骤如下:
准备必要库
从CircuitPython官方库包中获取以下文件,放到Pico W的lib文件夹中:adafruit_httpserver.mpyadafruit_connection_manager.mpy
完整实现代码
以下代码可创建软AP并启动一个简单的Web服务器:
import wifi import socketpool import time from adafruit_httpserver import Server, Request, Response # 配置AP参数 AP_SSID = "myAP" AP_PASSWORD = "password123" # 创建并激活软AP wifi.radio.start_ap(ssid=AP_SSID, password=AP_PASSWORD) print(f"AP已启动,SSID: {AP_SSID}") print(f"AP IP地址: {wifi.radio.ipv4_address_ap}") # 创建socket池 pool = socketpool.SocketPool(wifi.radio) # 启动Web服务器 server = Server(pool, "/static", debug=True) # 定义路由,处理根路径请求 @server.route("/") def base(request: Request): return Response(request, "Hello from Pico W AP Web Server!", content_type='text/plain') # 启动服务器 server.start(str(wifi.radio.ipv4_address_ap)) print("Web服务器已启动") # 循环处理客户端请求 while True: server.poll() time.sleep(0.1)
- 关键说明
- 用
wifi.radio.start_ap()启动软AP,可按需配置信道、最大连接数等参数 - 通过
wifi.radio.ipv4_address_ap直接获取AP的IP地址 adafruit_httpserver库简化了Web服务器的搭建,支持路由定义、静态文件服务等常用功能- 主循环中需持续调用
server.poll()来处理客户端的请求
- 用
内容的提问来源于stack exchange,提问作者Baseed
相关产品推荐
相关产品推荐

