cat /dev/tty.PL2303-... again...

Help
Jon Riehl
2010-06-30
2013-04-22
  • Jon Riehl
    Jon Riehl
    2010-06-30

    Hi all,

    I've noted that a lot of people are trying to just read stuff directly from the device, and this doesn't seem to work unless the device at the other end is using 9600 baud.  Since I'm talking to an AVR system, this doesn't work for me, since it wants to talk at 115200 baud.  I still can't get "cat /dev/tty.PL2303-…" to work (I wasn't able to determine if this is stty's fault or the driver's), but I did a dtrace on "screen /dev/tty.PL2303-… 115200" and figured out what needs to happen to get Python to set the baud rate for me.  The following Python script will accomplish the same thing as "cat" should when the baud rate is set properly:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    #! /usr/bin/env python
    # ______________________________________________________________________
    """Script readusbtty.py
    Reads from the serial-to-USB device and outputs to stdout.
    Jonathan Riehl - http://jonriehl.com/
    """
    # ______________________________________________________________________
    # Module imports
    import os
    import termios
    import time
    # ______________________________________________________________________
    # Module data
    BAUD_RATE = 115200
    TIME_OUT = 0.01 # Wait this many seconds before trying to reread from the port.
    DEFAULT_DEVICE = "/dev/tty.PL2303-0000201A"
    # ______________________________________________________________________
    # Main routine
    def main (*args):
        # Find and open the serial device.
        if len(args) > 1:
            devname = args[0]
        else:
            devname = DEFAULT_DEVICE
        # I'm not sure that NOCTTY needs to be set, but I saw screen do
        # it, so I'll play along.
        fd = os.open(devname, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)
        # Set the baud rate.
        attrs = termios.tcgetattr(fd)
        attrs[4] = attrs[5] = BAUD_RATE
        termios.tcsetattr(fd, termios.TCSANOW, attrs)
        # Indefinitely output what we're reading.
        while 1:
            try:
                data = os.read(fd, 1024)
                os.write(1, data)
            except OSError:
                # OSError gets raised when there is nothing to read, so
                # just timeout briefly, and try again.
                time.sleep(TIME_OUT)
    # ______________________________________________________________________
    if __name__ == "__main__":
        import sys
        main(*sys.argv[1:])
    # ______________________________________________________________________
    # End of readusbtty.py