pyusb使用
1、安装pyusb
pip install pyusb
安装完成后运行以下代码查找所有usb设备
import usb.util
# with pure PyUSB
for dev in usb.core.find(find_all=True):
print(dev)
注意:如果出现usb.core.NoBackendError: No backend available报错则说明需要安装libusb
2、安装libusb
pip install pyocd
查找所有usb设备
import libusb_package
# with pyocd/libusb-package
for dev in libusb_package.find(find_all=True):
print(dev)
print("-------"*10)
3、往usb写入数据
import usb.core
import usb.util
import os
import libusb_package
import usb.backend.libusb1
libusb1_backend = usb.backend.libusb1.get_backend(find_library=libusb_package.find_library)
dev = usb.core.find(idVendor=0x03eb, idProduct=0x2421, backend=libusb1_backend)
# print("dddd:", dev)
# was it found?
if dev is None:
raise ValueError('Device not found')
# set the active configuration. With no arguments, the first
# configuration will be the active one
dev.set_configuration()
packet = [85, 170, 17, 1, 0, 31, 102, 153]
packet = packet + (64-len(packet))*[0]
dev.write(0x01, packet, timeout=1000)
data = dev.read(0x81, 64, timeout=1000)
print(data)
获取配置信息并配置usb然后读取数据
import usb.core
import usb.util
import os
import libusb_package
import usb.backend.libusb1
libusb1_backend = usb.backend.libusb1.get_backend(find_library=libusb_package.find_library)
dev = usb.core.find(idVendor=0x03eb, idProduct=0x2421, backend=libusb1_backend)
# was it found?
if dev is None:
raise ValueError('Device not found')
dev.set_configuration()
cfg = dev.get_active_configuration()
intf = cfg[(0, 0)]
# match the first OUT endpoint
epo = usb.util.find_descriptor(intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT)
epi = usb.util.find_descriptor(intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN)
# print("eeeee11: ", epo)
# print("eeeee22: ", epi)
packet = [85, 170, 17, 1, 0, 31, 102, 153]
packet = packet + (64-len(packet))*[0]
epo.write(packet, timeout=1000)
data = epi.read(64, timeout=1000)
print(data)
注意:当遇到usb.core.USBError: [Errno 5] Input/Output Error报错时
1)检查usb打开的是否正确
2)检查写入的数据长度是否正确
3)检查写入的端点是否正确,往usb写如家要往“ENDPOINT 0x1: Interrupt OUT”中写数据,读数据要从“ENDPOINT 0x81: Interrupt IN”中读数据
标签:usb,pyusb,dev,packet,使用,import,find,backend From: https://www.cnblogs.com/chen55555/p/18006126