Search code examples
pythonpython-2.7serial-portraspberry-piuart

Read/Write Serial data in Python in semi-realtime (<0.1 second delay)


I would like to read and write to a serial connection at /dev/ttyUSB0 with the baud rate of 115200. [It might also be relevant that it uses the PL2303 chipset] Is there a way to do this in python 2.7, via print and raw_input statements?


Solution

  • The term you are looking for is baud rate. 115200 baud means that the serial port is able to transfer 115200 bits (:read BITS) per second. That is a fairly common baud rate so that should not be an issue as long as your USB UART can keep up. I have this one super old FTDI USB UART that is unreliable over 19200 but that is the only one that ever gives me grief. Symptoms of a bad cable are mangled, missing characters in your responses and transmissions.

    I don't think you can use print or raw_input for serial processing. If you can, I don't see any reason to because that is not what they are designed for. What you want to use is the pyserial module: https://github.com/pyserial/pyserial

    I have this project https://github.com/PyramidTechnologies/Python-RS-232 that runs on Raspberry Pi just fine. Key points for implementation:

        ser = serial.Serial(
            port=portname,
            baudrate=115200,
            bytesize=serial.SEVENBITS,
            parity=serial.PARITY_EVEN,
            stopbits=serial.STOPBITS_ONE
        )
    

    Be sure to set to whatever your target device speaks

    Then for reading and writing, setup some flow control like this:

    // msg could be a list of numbers. e.g. [4, 56, 34, 213]
    ser.write(msg)
    
    // Experiment with delay before reading if you are not getting
    // a response right away.
    time.sleep(0.1)
    
    // Keep reading from port while there is data to read
    out = ''
    while ser.inWaiting() > 0:
        out += ser.read(1)
        if out == '':
            continue
    
    // out is now the received bytes
    // https://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.read