[PYTHON] READ SERIAL DATA - fourslickz/notes GitHub Wiki

import serial
import time

# Replace 'COM3' with your serial port (e.g., '/dev/ttyUSB0' on Linux)
ser = serial.Serial('COM3', baudrate=9600, timeout=1)

# Wait for the serial connection to initialize
time.sleep(2)

# Read data in a loop
try:
    while True:
        if ser.in_waiting > 0:  # Check if there is data waiting to be read
            data = ser.readline().decode('utf-8').strip()  # Read a line and decode it
            print(f"Received: {data}")
except KeyboardInterrupt:
    print("Exiting program.")

# Close the serial port
finally:
    ser.close()