- 1 year ago
Python Serial on Windows: USB monitor loop while reading serial information does not work
To create a USB monitor loop while reading serial information using the pyserial
library in Python on Windows, you can follow these steps:
Install the
pyserial
library if you haven't already. You can use the following command to install it:shellpip install pyserial
Import the necessary modules in your Python script:
pythonimport serial
import serial.tools.list_ports
Use the
serial.tools.list_ports.comports()
function to get a list of available serial ports:pythonavailable_ports = serial.tools.list_ports.comports()
Loop through the list of available ports and open the serial connection:
pythonfor port in available_ports:
ser = serial.Serial(port.device, baudrate=9600)
print("Connected to port:", ser.name)
while True:
data = ser.readline().decode().strip()
if data:
print("Received data:", data)
ser.close() # Close the serial connection when done
Note that in this example, the script will continuously read data from the serial port until it is interrupted.
Make sure to replace the baudrate (9600
in this example) with the appropriate value for your specific device.
Remember to handle any exceptions that may occur during the execution of the script, such as SerialException
or KeyboardInterrupt
, to ensure proper error handling and termination of the program.
By running this script, you should be able to monitor the serial data coming from the connected USB device on Windows.