[Python] Python: What's blocking me from writing / reading from serial port in Ubuntu Linux?

Discussão em 'Python' iniciado por Stack, Maio 28, 2025.

  1. Stack

    Stack Membro Participativo

    I've created this Python script to distill the problem down to it's most fundamental. This works on Windows against COM3 (my Arduino programmed to return data via serial).

    Why doesn't this work on Ubuntu Linux using /dev/tty2. I have added myself to the group and given the the serial object reports that it's connected. But nothing happens after connection. (I can also see that /dev/tty1 and /dev/tty3 DO NOT connect, so that tells me my permissions are good on /dev/tty2, no?)

    I'd actually prefer to connect to /dev/tty1, but have been unable to get my permissions to connect to that one.

    Any help greatly appreciated. Best wishes.

    # This test file will write / read to a COM port on Windows but not on
    # Ubuntu Linux against "/dev/tty2". Why?


    import serial

    while True:

    try:
    ser = serial.Serial('/dev/tty2', 9600, timeout = 1)

    if ser:
    print("Connected to: ", ser.name)

    except serial.SerialException as e:
    print(f"Error opening serial port: {e}")
    exit()

    try:
    ser.write(b"Test from Python\n")

    while True:
    data = ser.readline()
    if data:
    print("Received: ", data.decode().strip())

    except Exception as e:
    print(f"Error during communication: {e}")
    finally:
    # Close the serial port
    if ser.is_open:
    ser.close()
    print("Serial port closed")

    Continue reading...

Compartilhe esta Página