pyserial timeout=1 || timeout=0.01
昨天在做串口通信时候发现,串口参数(timeout=1 || timeout=0.01)对通信的读数据竟然影响很大,代码如下:
self.ser = serial.Serial(port=serialName,
timeout=0.01,
baudrate=115200,
parity=serial.PARITY_ODD)
- timeout = 1:串口读取数据特别慢
- timeout = 0.01:串口读取数据正常
吓得我赶紧查看下官方文档:
- timeout = None: wait forever / until requested number of bytes are received
- timeout = 0: non-blocking mode, return immediately in any case, returning zero or more, up to the requested number of bytes
- timeout = x: set timeout to x seconds (float allowed) returns immediately when the requested number of bytes are available, otherwise wait until the timeout expires and return all bytes that were received until then.
显然,我个人用的就是第三种赋值方法,这个解释就是:在设定的timeout时间范围内,如果读取的字节数据是有效的(就是非空)那就直接返回,否则一直会等到这个设定的timeout时间并返回这段时间所读的全部字节数据。
分析下代码:
#read data
def ReadData(self,timeDelay):
bReadData = False
for i in range(0, 5, 1):
time.sleep(timeDelay)
readString = self.ser.readline()
if(len(readString) > 1):
return readString
else:
continue
if(bReadData == False):
return "fail"
发现读取数据用的是readline()这个函数,那具体实现机制会是怎样呢,个人理解如下:
1、Python2的内置编码是ASCII码
2、官方文档给出的解释是针对一串字符串而言,但readline()函数的操作对象肯定是单字节
3、单字节在读取的时候是有一定的时间间隔的,即读完一个字节隔段时间再读一个字节
4、这个时间间隔很有可能和timeout值成正比