如何通过USB线缆使用Python/MicroPython读写Raspberry Pi Pico数据
通过USB实现Raspberry Pi Pico的数据读写(Python/MicroPython)
核心思路
Raspberry Pi Pico默认支持USB CDC(虚拟串口),可通过这个通道实现PC与Pico的双向数据传输。下面分Pico端(MicroPython)和PC端(Python)给出具体实现方案。
Pico端(MicroPython)代码
将以下代码保存为main.py并上传到Pico,重启后Pico会通过USB虚拟串口监听并主动发送数据:
import usb_cdc import time # 初始化USB数据串口(默认波特率115200) serial_port = usb_cdc.data while True: # 监听PC发送的数据 if serial_port.in_waiting > 0: received = serial_port.readline().decode('utf-8').strip() print(f"PC发来: {received}") # 回复确认信息 serial_port.write(f"已收到: {received}\n".encode('utf-8')) # 主动发送模拟传感器数据(每隔2秒) time.sleep(2) mock_data = f"模拟数据: {time.time()}" serial_port.write(f"{mock_data}\n".encode('utf-8'))
PC端(Python)代码
首先安装依赖库:
pip install pyserial
使用以下代码与Pico通信(注意根据系统修改端口号):
import serial import time # 替换为你的Pico串口端口 # Windows: COMx(设备管理器中查看) # Linux: /dev/ttyACM0 # macOS: /dev/tty.usbmodemxxxx PORT = "/dev/ttyACM0" BAUD_RATE = 115200 # 打开串口,等待连接稳定 ser = serial.Serial(PORT, BAUD_RATE, timeout=1) time.sleep(2) try: while True: # 发送数据到Pico user_input = input("输入要发送的内容: ") ser.write(f"{user_input}\n".encode('utf-8')) # 读取Pico的回复 response = ser.readline().decode('utf-8').strip() if response: print(f"Pico回复: {response}") # 读取Pico主动推送的数据 while ser.in_waiting > 0: active_data = ser.readline().decode('utf-8').strip() print(f"Pico推送: {active_data}") time.sleep(0.1) except KeyboardInterrupt: print("\n断开连接") ser.close()
进阶:结构化数据传输
如果需要传输复杂数据(比如传感器读数),可以用JSON格式统一解析:
Pico端修改
import json # ... # 模拟传感器数据 sensor_readings = {"temp": 26.3, "humidity": 58} serial_port.write(json.dumps(sensor_readings).encode('utf-8') + b"\n")
PC端修改
import json # ... data = ser.readline().decode('utf-8').strip() if data: try: readings = json.loads(data) print(f"温度: {readings['temp']}°C | 湿度: {readings['humidity']}%") except json.JSONDecodeError: print(f"无法解析的数据: {data}")
注意事项
- 确保Pico的USB数据串口未被禁用(默认启用,若修改过
boot.py需检查) - 端口号需根据操作系统和设备实际情况调整
- 波特率必须与Pico端保持一致
- Linux/macOS若出现权限问题,可将用户加入
dialout组(Linux)或修改端口权限
内容的提问来源于stack exchange,提问作者basil_man
相关产品推荐
相关产品推荐

