USB serial communication and application of pyusb library
USB Serial Communication and Applications of the pyusb Library
USB (Universal Serial Bus) is a universal interface standard for transferring data between computers and external devices. In practical applications, we often use USB serial ports for inter-device communication, such as connecting sensors, printers, scanners, and other external devices.
In Python, we can use the pyusb library to implement USB serial communication. pyusb is a Python-implemented USB library for controlling USB devices. By using the pyusb library, we can easily read and write USB devices from Python programs.
Installing the pyusb Library
Before using the pyusb library, we need to install it. You can install the pyusb library using the pip tool with the following command:
pip install pyusb
Once the installation is complete, we can begin using the pyusb library for USB serial communication.
USB Device Identification
Before using the pyusb library to communicate with a USB device, we need to confirm the USB device’s identification information in the system, including the device’s vendor ID and product ID. These two pieces of information will help us correctly identify and connect to the USB device.
We can use the lsusb
command to view information about connected USB devices. The following example shows the output of the lsusb
command, using an Arduino development board connected to a computer as an example:
Bus 001 Device 003: ID 2341:0043 XYZ Corporation Arduino Uno
<p>In this output, 2341 is the manufacturer ID of the Arduino Uno, and 0043 is the product ID.
<h2>Using the pyusb Library for USB Serial Communication</h2>
<p>Next, we'll demonstrate how to use the pyusb library to communicate with a USB device. In this example, we'll communicate with the Arduino development board over the USB serial port to control a simple LED. </p>
<p>First, we need to create a Python script that imports the pyusb library and defines the USB device's vendor and product IDs:</p>
<pre><code class="language-python line-numbers">import usb.core
import usb.util
# Define the USB device's vendor and product IDs
VENDOR_ID = 0x2341
PRODUCT_ID = 0x0043
Next, we need to write a function to connect to the USB device and open its endpoints:
def connect_to_arduino():
# Find a USB device with the specified vendor and product IDs
dev = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)
if dev is None:
raise ValueError("Device not found")
# Open the device
dev.set_configuration()
# Get the device's endpoint
cfg = dev.get_active_configuration()
interface_number = cfg[(0, 0)].bInterfaceNumber
alternate_setting = usb.control.get_interface(interface_number)
intf = usb.util.find_descriptor(
cfg, bInterfaceNumber = interface_number,
bAlternateSetting = alternate_setting
)
out_endpoint = usb.util.find_descriptor(
intf,
custom_match = lambda e:
usb.util.endpoint_direction(e.bEndpointAddress) ==
usb.util.ENDPOINT_OUT
)
in_endpoint = usb.util.find_descriptor(
intf,
custom_match = lambda e:
usb.util.endpoint_direction(e.bEndpointAddress) ==
usb.util.ENDPOINT_IN )
assert out_endpoint is not None and in_endpoint is not None
return dev, out_endpoint, in_endpoint
Next, we’ll write a function to send commands to the Arduino board:
def send_command(dev, out_endpoint, command):
dev.write(out_endpoint.bEndpointAddress, command)
Finally, we’ll write a function to receive data from the Arduino board:
def receive_data(dev, in_endpoint):
return dev.read(in_endpoint.bEndpointAddress, in_endpoint.wMaxPacketSize)
Now, we can call the functions defined above to implement LED control. Here is a complete Python script example:
import usb.core
import usb.util
VENDOR_ID = 0x2341
PRODUCT_ID = 0x0043
def connect_to_arduino():
dev = usb.core.find(idVendor=VENDOR_ID, idProduct=PRODUCT_ID)
if dev is None:
raise ValueError("Device not found")
dev.set_configuration()
cfg = dev.get_active_configuration()
interface_number = cfg[(0, 0)].bInterfaceNumber
alternate_setting = usb.control.get_interface(interface_number)
intf = usb.util.find_descriptor(
cfg, bInterfaceNumber = interface_number,
bAlternateSetting = alternate_setting )
out_endpoint = usb.util.find_descriptor(
intf,
custom_match = lambda e:
usb.util.endpoint_direction(e.bEndpointAddress) ==
usb.util.ENDPOINT_OUT
)
in_endpoint = usb.util.find_descriptor(
intf,
custom_match = lambda e:
usb.util.endpoint_direction(e.bEndpointAddress) ==
usb.util.ENDPOINT_IN
)
assert out_endpoint is not None and in_endpoint is not None
return dev, out_endpoint, in_endpoint
def send_command(dev, out_endpoint, command):
dev.write(out_endpoint.bEndpointAddress, command)
def receive_data(dev, in_endpoint):
return dev.read(in_endpoint.bEndpointAddress, in_endpoint.wMaxPacketSize)
if __name__ == "__main__":
dev, out_endpoint, in_endpoint = connect_to_arduino()
while True:
# Send a command to control the LED
command = input("Enter command (1 for on, 0 for off): ")
send_command(dev, out_endpoint, command.encode('utf-8'))
# Receive data from the Arduino
data = receive_data(dev, in_endpoint)
print(f"Received data: {data}")
In the above code, we establish USB serial communication with the Arduino development board and control the on/off state of the LED by sending commands. We continuously loop to send commands and receive data from the Arduino development board.
Running the Example Code
Before running the above example code, you need to connect the Arduino development board to your computer and ensure that it is working properly.
Use Python to run the example code and enter commands to control the LED’s on and off state. You can then see the LED’s on and off state and view the data sent by the Arduino development board.
Using the pyusb library, we can easily implement USB serial communication and exchange data with various USB devices, facilitating project development.
Summary
This article introduced the basic principles of USB serial communication and how to use the pyusb library to operate USB devices in Python. Through example code, we demonstrated how to communicate with an Arduino development board via USB serial to implement LED control.
USB serial communication is widely used in various embedded devices, external sensors, and other scenarios. Through appropriate protocol design and communication method selection, stable and efficient data exchange can be achieved.