Python PySerial read-line timeout
Asked Answered
D

2

11

I'm using pyserial to communicate with a embedded devise.

ser = serial.Serial(PORT, BAUD, timeout = TOUT)
ser.write(CMD)
z = ser.readline(eol='\n')

So we send CMD to the device and it replies with an string of varing length ending in a '\n'

if the devise cant replay then readline() times-out and z=''

if the devise is interrupted or crashes will it's sending the data then readline() times-out and z will be a string without a '\n' at the end.

Is there a nice way to check if readline() has timed-out other than checking the state of z.

Dated answered 9/8, 2010 at 4:14 Comment(0)
C
5

I think what you might like to do is..

import re
import time
import serial

def doRead(ser,term):
    matcher = re.compile(term)    #gives you the ability to search for anything
    tic     = time.time()
    buff    = ser.read(128)
    # you can use if not ('\n' in buff) too if you don't like re
    while ((time.time() - tic) < tout) and (not matcher.search(buff)):
       buff += ser.read(128)

    return buff

if __name__ == "__main__":
    ser = serial.Serial(PORT, BAUD, timeout = TOUT)
    ser.write(CMD)
    print doRead(ser,term='\n')
Couchant answered 9/8, 2010 at 4:51 Comment(1)
Why do you use a regex? Wouldn't a if '\n' in buff be more performant and shorter?Voltaic
S
0

PySerial has read_until method exactly for this, it reads the serial until an expected sequence is found (‘\n’ by default), the size is exceeded or until timeout occurs.

Steroid answered 22/1 at 15:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.