- 1 year ago
Recognition of a specific USB device in python
Comment
1 / 1
To recognize a specific USB device in Python, you can use the pyusb
module. Here is a sample code that demonstrates how to detect and interact with a USB device using pyusb
:
pythonimport usb.core
import usb.util
# find USB device using vendor and product ID
dev = usb.core.find(idVendor=0x1234, idProduct=0x5678)
# if device not found, raise exception
if dev is None:
raise ValueError('Device not found')
# set device configuration
dev.set_configuration()
# get an endpoint instance
cfg = dev.get_active_configuration()
interface_number = cfg[(0,0)].bInterfaceNumber
endpoint = cfg[(interface_number,0)]
# write data to device
data = "Hello World!"
try:
# send data to device
ret = dev.write(endpoint.bEndpointAddress, data, 100)
print(f"Sent {ret} bytes to device")
except usb.core.USBError as e:
print(f"Error sending data: {e}")
# read data from device
try:
# read up to 100 bytes from device
data = dev.read(endpoint.bEndpointAddress, 100)
print(f"Received {len(data)} bytes from device")
except usb.core.USBError as e:
print(f"Error reading data: {e}")
# release device
usb.util.release_interface(dev, interface_number)
usb.util.dispose_resources(dev)
In the above code, replace the idVendor
and idProduct
values with the vendor and product IDs of the USB device you want to recognize.