import serial import time # Configure the serial port # Replace 'COM4' (Windows) or '/dev/ttyACM0' (Linux/Mac) with your Arduino's port # Ensure the baud rate matches the one used in your Arduino sketch (e.g., Serial.begin(9600)) port = '/dev/ttyACM0' baud_rate = 9600 timeout = 1 try: # Open the serial port ser = serial.Serial(port, baud_rate, timeout=timeout) time.sleep(2) # Wait for the connection to establish (Arduino reset delay) print("Listening for messages...") while True: # Check if data is available if ser.in_waiting > 0: # Read a line from the serial port message = ser.readline().decode('utf-8').rstrip() print(f"Received: {message}") except serial.SerialException as e: print(f"Error opening serial port: {e}") except KeyboardInterrupt: print("\nExiting...") finally: if 'ser' in locals() and ser.is_open: ser.close() print("Serial port closed.")