How can Python read USB data?

In Python, you can use the pyserial library to read USB data.

Firstly, you need to install the pyserial library. You can install it using the following command:

pip install pyserial

The steps for reading USB data are as follows:

  1. Import the pyserial library.
import serial
  1. Create a serial port object:
ser = serial.Serial('/dev/ttyUSB0', 9600)  # 根据实际情况修改串口号和波特率
  1. Read data:
data = ser.read()  # 读取一个字节的数据

Or

data = ser.readline()  # 读取一行数据(以换行符结尾)
  1. Close the serial port.
ser.close()

The complete sample code is provided below:

import serial

ser = serial.Serial('/dev/ttyUSB0', 9600)

while True:
    data = ser.readline()
    print(data)

ser.close()

In the code above, ‘/dev/ttyUSB0’ is the path to the USB serial device, which can be modified according to the actual situation. 9600 is the baud rate, which can also be modified according to the actual situation. Then, continuously read and print out the data using a loop.

bannerAds