Search code examples
pythonserial-portpyserialserial-communication

read several lines from serial connection until condition is met, then allow serial write action


This is my current code, it does not seem to handle writes very well. It seems to be stuttering.

import serial

ser = serial.Serial(port='/dev/tty1', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1)

while True:
    line = ser.readline() 
    print line,

    if line == "":
        var = raw_input()

        if var != "":
            ser.write(var)    

I am trying to read several paragraphs of text, with a blank line separating each paragraph. when all the paragraphs are read, my pyserial script will then write a command to the serial channel, and then more paragraphs will be read, and so on.

How do I improve this?

---EDIT---------

Instead of raw_input(), I am now using select. Writing to the serial channel is ok now. but for the reading, somehow it just refuses to read/print the last paragraph.

Can anyone help?

import serial
import select
import sys

ser = serial.Serial(port='/dev/tty1', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1)

while True:

    line = ser.readline()
    print line,

    while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        lineIn = sys.stdin.readline()
        if lineIn:
            ser.write(lineIn)       
    else:
        continue

Solution

  • Why not follow-up on Joran Beasley's suggestion?

    import serial
    
    ser = serial.Serial(
        port='/dev/tty1',
        baudrate=115200,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        timeout=1)
    
    while True:
        line = ser.readline()
        if not line.strip():  # evaluates to true when an "empty" line is received
            var = raw_input()
            if var:
                ser.write(var)
        else:
            print line,
    

    It's more pythonic and readable than binding sys.stdin in a while construct... O_o