使用超时功能读取和写入UART pyserial

时间:2018-11-01 06:35:32

标签: python-3.x timeout embedded pyserial uart

我已经写了一个UART py-serial脚本,看起来像。

import serial
import time

try:
     ser = serial.Serial(
     #port='/dev/ttyAMA0',
     port='/dev/ttyUSB1',
     baudrate = 9600,
     parity=serial.PARITY_NONE,
     stopbits=serial.STOPBITS_ONE,
     bytesize=serial.EIGHTBITS,
     timeout=2
    )
    print ('Connection is open : ',str(ser.isOpen()))
except Exception as e:
    print ("Something got wrong: ", e)


ser.write(b'hello..')

,并且具有与接收方相似的脚本。

我想要的是: 假设超时= 5

ser.write(b'Helloo...')
ser.flush()
ser.readline()

另一个脚本正在读取它,并且仅通过串行发送响应。 该readline应该为此超时等待最大的时间,如果它在2秒内收到响应,则不应等待5秒。

但是使用此超时,即使一秒钟内接收到数据,它也会等待2秒。

所以我担心的是等待最大超时时间,但是如果较早收到数据,则应该结束并继续。

找不到此功能,请提供帮助。

1 个答案:

答案 0 :(得分:0)

找到了一种可行的方法:

pyserial具有此inbuit功能,例如:

ser.read_until(b'#') #just specify EOL here

如果找到此(#),它将中断。如果没有,将等待超时并最终返回。

您还可以使用单独的超时进行读写:

timeout=5 #read timeout
write_timeout=5 # write timeout
相关问题