如何同时检查串行输入和键盘输入(同时使用readchar和串行库)

2024-06-28 18:44:49 发布

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

我尝试在树莓pi中使用python3编写以下代码:

1)等待14位条形码(条形码扫描仪通过usb端口连接,输入作为键盘数据接收)

2)读取条形码后,等待串行通信(设备连接到usb端口并发送串行命令)。可以是一个或多个……)其思想是接收到的所有命令都将与扫描的条形码相关联

3)读取新条形码时,等待串行命令的过程必须停止。这是我还没弄明白怎么做的部分

经过一些研究,我决定使用“readchar”库作为条形码扫描仪,使用“serial”库作为串行通信接收。它们都是自己工作的,但问题是当我试图同时检测这两种东西时。你知道吗

在下面的代码中,我成功地读取了一个条形码,然后等待5行串行通信,最后重复这个过程并再次读取条形码。该程序的工作,因为它是现在,但问题是,我不知道有多少线的串行通信,我会收到,所以我需要以某种方式检测一个新的条形码,同时也等待接收串行通信。你知道吗

import readchar
import time
import serial

ser = serial.Serial(
 port='/dev/ttyUSB0',
 baudrate = 115200,
 parity=serial.PARITY_NONE,
 stopbits=serial.STOPBITS_ONE,
 bytesize=serial.EIGHTBITS,
 timeout=1
)

print("Waiting for barcode...")
while 1:
    inputStr = ""
    while len(inputStr) != 14:  #detect only 14 digit barcodes
        inputStr += str(readchar.readchar())
        inputStr = ''.join(e for e in inputStr if e.isalnum())  #had to add this to strip non alphanumeric characters           
    currentCode = inputStr
    inputStr = ""
    print(currentCode)
    ser.flushInput()
    time.sleep(.1)

    # Wait for 5 lines of serial communication
    # BUT it should break the while loop when a new barcode is read!
    count = 0  
    while count < 5:
        dataRead=ser.readline()
        if len(dataRead) > 0:
            print(dataRead)
            count+=1

    print("Waiting for barcode...")

如果我在while循环中添加一个条件(序列号readline())以便如果从扫描仪读取字符(readchar.readchar文件())那就把事情搞砸了。这就像readline和reacher不能在同一while循环中一样。你知道吗

做一些研究,我认为我需要使用异步IO,线程或类似的东西,但我没有线索。我也不知道我是否可以继续使用相同的库(serial和readchar)。请帮忙


Tags: import命令forreadlinecountserialbarcodeser
2条回答

我不能确定(我没有你的条形码阅读器和串口设备),但根据你说的,我认为你不需要线程,你只需要依靠缓冲区来保存你的数据,直到你有时间读取它们。你知道吗

只需将第二个while循环的条件更改为:

while serial.inWaiting() != 0:

这样,您将确保您的串行端口上的接收缓冲区将清空。根据设备的速度和时间,这种方法可能有效,也可能无效。你知道吗

您还可以尝试在缓冲区清空后添加一个短暂的延迟:

import serial
import time
ser=serial.Serial(port="/dev/ttyUSB0",baudrate=115200, timeout=1.0)          
time.sleep(1)
data=b""
timeout = time.time() + 1.0
while ser.inWaiting() or time.time()-timeout < 0.0:   #keep reading until the RX buffer is empty and wait for 1 seconds to make sure no more data is coming
    if ser.inWaiting() > 0:
        data+=ser.read(ser.inWaiting())
        timeout = time.time() + 1.0
    else:
        print("waiting...")

这会在接收到最后一个字节后的1秒内一直尝试从端口读取数据,以确保没有其他数据。您可能希望根据设备的速度和时间来调整延迟的持续时间。你知道吗

再说一次,我没有你的设备,所以我无法判断,但是你从条形码/键盘读取字符的方式看起来远不是最佳的。我怀疑readchar是最好的方法。最后,你的条形码阅读器可能是一个串行端口。你可能想深入研究一下,或者找到一种更有效的方法来一次性阅读几个键盘笔划。你知道吗

我在另一个问题中找到了这个答案:

How to read keyboard-input?

我试过了,而且很管用!我也将尝试一下marcosg提出的方法

相关问题 更多 >