Skip to content

Instantly share code, notes, and snippets.

@0XDE57
Created July 26, 2025 07:41
Show Gist options
  • Save 0XDE57/54af0d81825e3a8b7107953d4a01b1ac to your computer and use it in GitHub Desktop.
Save 0XDE57/54af0d81825e3a8b7107953d4a01b1ac to your computer and use it in GitHub Desktop.
function to open serial port and listen to messages. be sure to set correct port and baud rate.
import serial
def listen_serial(port, baud_rate):
try:
ser = serial.Serial(port, baud_rate)
print(f"Opened {port} with baud rate {baud_rate}")
while True:
# Read data from the serial port
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').rstrip()
print(line)
except serial.SerialException as e:
print(f"Error opening or using the serial port: {e}")
except KeyboardInterrupt:
print("Program terminated by user.")
finally:
if ser.is_open:
ser.close()
print("Closed the serial port.")
def main():
port = '/dev/ttyACM0'
baud_rate = 9600
listen_serial(port, baud_rate)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment