You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Raspberry Pi Pico上用MicroPython不依赖pyserial读取USB设备

在Raspberry Pi Pico的MicroPython中读取USB串口设备(替代pyserial)

MicroPython没有pyserial库,可根据你的硬件连接场景选择以下方案:

方案1:通过硬件UART外接USB转串口模块

如果你的USB设备是通过USB转串口模块(如CH340、PL2303)连接到Pico的GPIO引脚,直接使用machine.UART模块即可,对应你原代码的参数实现如下:

import machine

# 初始化UART:对应波特率115200、8位数据、无校验、1位停止位,超时12秒(单位毫秒)
uart = machine.UART(
    0,
    baudrate=115200,
    bits=8,
    parity=None,
    stop=1,
    timeout=12000
)

try:
    # 读取一行数据(换行符终止)
    raw_msg = uart.readline()
    if raw_msg:
        decoded = raw_msg.decode('ascii').strip()
        print(decoded)
    else:
        print("超时未获取到数据")
except Exception as e:
    print(f"串口操作出错: {e}")
finally:
    # 释放UART资源
    uart.deinit()

硬件连接提示

  • Pico的UART0对应引脚:GP0(TX)、GP1(RX),UART1对应GP4(TX)、GP5(RX)
  • USB转串口模块的TX接Pico的RX,RX接Pico的TX,GND共地,VCC接3.3V(注意模块的电压兼容)

方案2:Pico自身作为USB CDC串口设备

如果是Pico通过自身USB口和电脑通信(电脑识别为COM/TTY设备),使用usb_cdc模块实现:

import usb_cdc

# 获取CDC数据串口(默认已启用)
serial = usb_cdc.data
# 设置超时12秒(单位毫秒)
serial.timeout = 12000

try:
    raw_msg = serial.readline()
    if raw_msg:
        decoded = raw_msg.decode('ascii').strip()
        print(decoded)
    else:
        print("超时未获取到数据")
except Exception as e:
    print(f"CDC串口操作出错: {e}")
finally:
    # 禁用CDC串口(可选,若后续无需通信)
    usb_cdc.data.enabled = False

方案3:Pico作为USB主机直接读取USB设备

如果要让Pico直接作为USB主机读取USB串口设备(如直接插USB设备到Pico的USB口),需要使用USB Host相关库,基于tinyusb的实现示例如下(需先刷入支持USB Host的MicroPython固件):

import usb.core
import usb.util

# 替换为你的USB串口设备的VID和PID(示例为CH340)
TARGET_VID = 0x1a86
TARGET_PID = 0x7523

# 查找目标设备
dev = usb.core.find(idVendor=TARGET_VID, idProduct=TARGET_PID)
if not dev:
    print("未找到目标USB设备")
    raise SystemExit

# 配置设备
dev.set_configuration()

# 获取输入端点
cfg = dev.get_active_configuration()
intf = cfg[(0, 0)]
ep = usb.util.find_descriptor(
    intf,
    custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN
)

try:
    # 读取最多64字节数据,超时12秒
    raw_msg = ep.read(64, timeout=12000)
    decoded = raw_msg.decode('ascii').strip()
    print(decoded)
except Exception as e:
    print(f"USB主机读取出错: {e}")
finally:
    # 释放设备资源
    usb.util.dispose_resources(dev)

内容的提问来源于stack exchange,提问作者Juliën

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:25:17