Created
July 26, 2025 07:41
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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