如何在CircuitPython中为树莓派Pico W搭建带软AP的Web服务器
Raspberry Pi Pico W CircuitPython AP模式Web服务器解决方案
问题原因
你遇到的TypeError是因为在AP模式下,CircuitPython需要通过wifi.radio.ipv4_address_ap获取AP的IP地址,而非wifi.radio.ipv4_address——后者是设备作为WiFi客户端(STA模式)时的IP。直接调用ipv4_address会返回None,导致socket绑定操作出现类型错误。
修正后的完整代码
以下是可正常运行的AP模式Web服务器代码,支持读取本地index.html文件返回给客户端:
import wifi import socketpool import os # 设置AP参数 ap_ssid = "myAP" ap_password = "password123" # 启用WiFi并启动AP wifi.radio.enabled = True wifi.radio.start_ap(ssid=ap_ssid, password=ap_password) # 获取AP的IP地址 ap_ip = wifi.radio.ipv4_address_ap print(f"Access point created with SSID: {ap_ssid}, password: {ap_password}") print(f"My AP IP address is {ap_ip}") # 创建socket池 pool = socketpool.SocketPool(wifi.radio) def read_index_html(): """读取本地index.html文件内容""" try: with open("index.html", "r") as f: return f.read() except OSError: # 如果文件不存在,返回默认页面 return "<html><body><h1>Error: index.html not found</h1></body></html>" def simple_http_server(): server_socket = pool.socket() # 绑定到AP的IP和80端口,也可以用""绑定到所有可用接口 server_socket.bind((ap_ip, 80)) server_socket.listen(1) print(f"Server is listening on {ap_ip}:80") while True: print("Waiting for a connection...") client_socket, client_address = server_socket.accept() print(f"Accepted connection from: {client_address}") try: # 读取客户端请求(简单处理,只响应GET请求) request = client_socket.recv(1024).decode("utf-8") print(f"Request received:\n{request}") # 准备响应头和内容 response_body = read_index_html() response = ( "HTTP/1.0 200 OK\r\n" f"Content-Length: {len(response_body)}\r\n" "Content-Type: text/html\r\n\r\n" f"{response_body}" ) # 发送响应 client_socket.send(response.encode("utf-8")) except Exception as e: print(f"Error handling request: {e}") finally: client_socket.close() # 启动服务器 simple_http_server()
关键修改点
- 替换
wifi.radio.ipv4_address为wifi.radio.ipv4_address_ap,正确获取AP模式下的IP地址 - 添加
wifi.radio.enabled = True语句,确保WiFi radio处于启用状态 - 新增
read_index_html函数,负责读取本地index.html文件,文件不存在时返回默认错误页面 - 完善HTTP响应格式,添加
Content-Length响应头,保证客户端能正确解析内容 - 增加异常处理逻辑,避免单个请求处理失败导致服务器崩溃
使用说明
- 在Pico W的CircuitPython文件系统中创建
index.html文件,写入自定义HTML内容 - 将上述代码保存为
code.py,上传到Pico W - 连接到名为
myAP的WiFi热点,密码为password123 - 在浏览器中访问终端打印的AP IP地址,即可看到
index.html的内容
内容的提问来源于stack exchange,提问作者Ahrorous
相关产品推荐
相关产品推荐

