Raspberry Pi Pico USB接收数据后停止工作的问题排查求助
Raspberry Pi Pico USB通信LED触发问题排查
我需要实现Raspberry Pi Pico通过USB接收数据时点亮LED一段时间,但目前运行后PC仅能收到一次Pico的输出,之后无响应,LED也不闪烁。
Pico端代码
import select import sys import machine poll_obj = select.poll() poll_obj.register(sys.stdin, select.POLLIN) counter = 0 pin = machine.Pin(25, machine.Pin.OUT) pin.value(0) while True: poll_results = poll_obj.poll(1) if poll_results: # Read the data from stdin (read data coming from PC) data = sys.stdin.read().strip() pin.value(1) # Write the data to the input file print("receivedL " + str(data)) else: counter = counter + 1 if(counter >= 1000): pin.value(0) counter = 0 print("test")
PC端代码
import serial s = serial.Serial(port="COM3", parity=serial.PARITY_EVEN, timeout=1) s.flush() data = s.read() while True: print(data) data = s.read() s.write("1".encode()) s.flush()
操作流程
- 插入Raspberry Pi Pico并运行代码(不使用Thonny或其他编辑器);
- 通过PuTTY连接USB端口验证代码正在运行;
- 断开PuTTY并运行PC端代码。
核心问题分析
- Pico端读取阻塞:
sys.stdin.read()默认会等待到EOF才返回,导致Pico在读取一次数据后陷入阻塞,无法回到主循环处理后续通信和LED逻辑。 - 串口配置不匹配:Pico的USB CDC串口默认无校验位,PC端设置了
PARITY_EVEN奇偶校验,会导致数据解析错误,Pico无法识别有效输入。 - LED计时逻辑不可靠:依赖循环计数的计时方式会因主循环阻塞完全失效,无法保证LED按时熄灭。
修复方案
修改Pico端代码
改用固定长度读取避免阻塞,用时间戳实现可靠的LED计时:
import select import sys import machine import time poll_obj = select.poll() poll_obj.register(sys.stdin, select.POLLIN) pin = machine.Pin(25, machine.Pin.OUT) pin.value(0) led_expire_time = 0 # 记录LED需要保持点亮的截止时间戳 while True: current_ms = time.ticks_ms() # 检查是否到了熄灭LED的时间 if current_ms > led_expire_time: pin.value(0) poll_results = poll_obj.poll(1) if poll_results: # 读取1字节数据,避免阻塞 data = sys.stdin.read(1).strip() if data: pin.value(1) led_expire_time = current_ms + 1000 # 保持点亮1秒 print(f"received: {data}")
修改PC端代码
匹配Pico默认串口配置,调整读取逻辑:
import serial import time # 匹配Pico默认串口参数:无校验、115200波特率 s = serial.Serial(port="COM3", baudrate=115200, parity=serial.PARITY_NONE, timeout=1) s.flush() while True: # 读取Pico输出的整行内容 data = s.readline() if data: print(data.decode().strip()) # 发送数据 s.write(b"1") s.flush() time.sleep(0.5) # 间隔发送,避免数据堆积
额外注意事项
- 确保Pico代码以
main.py文件名存储在Pico的文件系统中,实现上电自动运行,避免依赖Thonny的REPL环境。 - 断开PuTTY后需等待数秒,确保串口端口完全释放,再运行PC端代码,避免端口占用冲突。
- 可先用串口调试工具(如串口助手)测试PC与Pico的通信,确认数据能正常收发后再运行代码。
内容的提问来源于stack exchange,提问作者cichyvx
相关产品推荐
相关产品推荐

