PySerial超时、CPU使用率和条形码扫描

2024-04-29 12:50:24 发布

您现在位置:Python中文网/ 问答频道 /正文

值得一提的是,虽然我有CS方面的背景,但我编写的Python脚本的数量很可能是根据树懒爪子上脚趾的数量来计算的。也就是说,我开始玩PySerial来读取USB条形码扫描仪。我遇到的一个问题是超时。如果我设置得太低,我就会错过扫描。如果我设置得太高,处理器利用率是巨大的。当然,PySerial的文档中提到了这一点:

Be careful when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines() only works with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.

是的。下面是我的简单代码:

#!/usr/bin/env python

import serial
ser = serial.Serial('/dev/ttyACM0', rtscts=True, dsrdtr=True, timeout=0.05)
ser.baudrate = 115200

while True:
    s = ser.readline()
    if s:
        print(s)

如何在不冒漏扫描风险的情况下正确地读取串行设备?当然,只有这么小的一个超时时间,几率非常低,但是我想在我的业务中使用它来进行生产,所以我们假设这是关键任务。解决这个问题的正确方法是什么(再次假设我对Python的理解是零)?在

谢谢大家!在

编辑:可能的解决方案?

我想出了以下不使用超时的方法,只需一次读取一个字符,直到它到达换行符为止。这似乎对处理器利用率影响不大(这是我遇到的全部问题)。当然,我需要考虑不同扫描仪的其他新线可能性,但这有什么原因不起作用吗?在

^{pr2}$

Tags: thetruereadline数量ifisporttimeout
1条回答
网友
1楼 · 发布于 2024-04-29 12:50:24

根据我对条形码扫描仪的了解,您可以配置它们,使它们只在您通过串行发送特定写入命令时触发扫描,您可以利用这一点。在

ser = serial.Serial('/dev/ttyUSBx',timeout=y)
ser.write('<trigger scan>')
value = ser.readline()
ser.close()

对于连续读取,最好的方法是在超时循环中继续读取字节,例如

^{pr2}$

相关问题 更多 >