最近在研究USB通讯,想用Python来实现,比较好用的一个库是PyUSB,但发现相关中文资料比较少,在这里做一个整理。系统是Windows 10 64位。
1.安装PyUSB
运行cmd用pip安装pyusb
pip install pyusb
2.测试
先打开设备管理器,随便找一个USB device,右键选择属性→详细信息→属性栏选择硬件ID,可以看到如下图所示的VID和PID。
运行以下脚本进行测试,usb.core.find(idVendor= 0x1908, idProduct= 0x0222)中的idVendor和idProduct改成上面查询到的VID和PID:
import usb.core
import usb.util
dev = usb.core.find(idVendor= 0x1908, idProduct= 0x0222)
if dev is None:
raise ValueError('Device not found')
print(dev)
# set the active configuration. With no arguments, the first
# configuration will be the active one
dev.set_configuration()
# get an endpoint instance
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]
ep = usb.util.find_descriptor(
intf,
# match the first OUT endpoint
custom_match = \
lambda e: \
usb.util.endpoint_direction(e.bEndpointAddress) == \
usb.util.ENDPOINT_OUT)
print(ep)
assert ep is not None
# write the data
ep.write('test')
如果正常会打印出来设备信息等内容:
3.安装问题解决:
(1)运行时报错:usb.core.NoBackendError: No backend available
点击下面的链接下载libusb-1.0.20的压缩包,解压后将MS64\dll\libusb-1.0.dll复制到C:\Windows\System32。如果还不行的话再将同一目录下的libusb-1.0.lib到Python路径下的lib\site-packages\usb文件夹中。
https://sourceforge.net/projects/libusb/files/libusb-1.0/libusb-1.0.20/libusb-1.0.20.7z/download
(2)代码能够执行到print(dev)并打印出设备信息,但执行dev.set_configuration()及之后的代码时报错:
NotImplementedError: Operation not supported or unimplemented on this platform
需要为设备安装WinUSB驱动,点击下面的链接下载Zadig,这是一个Windows平台上专门用于安装USB相关驱动的小软件,下载后可直接运行。
软件界面如下图所示,如果当前插入的USB设备都已经安装了驱动(我们常用的键鼠、U盘等都是自动安装了驱动的),这里的设备选择栏里就会没有设备,因为现在显示的是没有安装驱动的USB设备。
点击Option,勾选List All Devices,就可以看到当前所有USB设备,选择想要操作的设备,驱动选择栏选择WinUSB,点击Install Driver即可安装驱动。
!!!注意:更改设备驱动将会导致该设备原来的功能不能使用,所以这里请谨慎操作,最好选择没用的设备或自己开发的USB设备进行测试
下面这个链接是Zadig的官方说明,供参考:
https://github.com/pbatard/libwdi/wiki/Zadig
(3)usb.core.USBTimeoutError: [Errno 10060] Operation timed out
换一个USB口看看是否能解决,我遇到这个问题的时候USB设备插在一个USB扩展器上,直接插到电脑的USB口上就不会报错了。
4.使用PyUSB
先放一个GitHub上的官方使用说明,我也还没有深入研究和使用,之后使用过程中持续更新。
https://github.com/pyusb/pyusb/blob/master/docs/tutorial.rst