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值成正比

转载于:https://www.cnblogs.com/YangARTuan/p/10794025.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值