我正在尝试在树莓派中使用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循环中添加一个条件,即使用(ser.readline())读取串行通信,则如果从扫描仪(readchar.readchar())读取了字符,则会使事情搞砸。就像readline和到达器不能在while循环中一样。
做一些研究,我认为我需要使用异步IO或线程或类似的东西,但是我不知道。我也不知道是否可以继续使用相同的库(串行和readchar)。请帮助
我不确定(我没有条形码阅读器和串行端口设备),但是根据您所说的,我认为您不需要线程,您只需要依靠缓冲区来保存数据,直到您有时间阅读它们。
我在另一个问题中找到了这个答案: