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

树莓派Pico运行代码找不到usb_hid库,如何获取并导入该库?

树莓派Pico usb_hid 模块导入失败解决方案

核心原因

usb_hid 是CircuitPython内置的标准模块,官方原版MicroPython固件未集成该模块,因此直接运行代码会触发导入失败报错。

操作步骤

  • 刷入CircuitPython固件
    按住Pico板载的BOOTSEL按键后接入电脑,此时电脑会弹出名为RPI-RP2的可移动磁盘,将适配树莓派Pico的CircuitPython固件(格式为uf2)拖入该磁盘,Pico会自动完成刷机并重启,重启后磁盘名称变为CIRCUITPY即代表刷机成功。
  • 部署adafruit_hid依赖
    获取adafruit_hid库的完整文件夹,将该文件夹放入CIRCUITPY磁盘根目录下的lib文件夹内,如果没有lib文件夹可以自行新建。
  • 修正原代码的语法错误
    原代码存在变量定义未换行、注释越界的问题,修正后可直接使用:
from machine import Pin
import usb_hid
import time as t
from adafruit_hid.mouse import Mouse

# 声明三个按钮对应的引脚
pulsador_uno = Pin(3, Pin.IN, Pin.PULL_UP)
pulsador_dos = Pin(7, Pin.IN, Pin.PULL_UP)
pulsador_tres = Pin(11, Pin.IN, Pin.PULL_UP)

m = Mouse(usb_hid.devices)

def main():
    if not pulsador_uno.value() or not pulsador_dos.value() or not pulsador_tres.value():
        print('Button pressed!')
        m.click(Mouse.LEFT_BUTTON)
    else:
        print('Button not pressed!')
        t.sleep(0.1) # 原3秒休眠会导致按键检测不灵敏,改为0.1秒更合理

while True:
    main()
  • 运行验证
    将修正后的代码保存为CIRCUITPY磁盘根目录下的code.py,Pico会自动运行该代码,按下任意一个接好的按钮即可触发鼠标左键点击动作。

内容的提问来源于stack exchange,提问作者Jeremias Davison

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:57:03