python - 来自串口的数据采用垂直格式
问题描述
我有一个使用条形码扫描仪从串行端口(TXRX)读取的python脚本,一切正常,但是当从串行端口输入文本时我的问题是垂直格式,如下所示:
如果我正在阅读的条形码有 123456,它在我的 python 脚本中为:
1
2
3
4
5
6
我试过改变 print() 选项,但似乎没有任何运气。
import sys
import serial
ser = serial.Serial("/dev/ttyAMA0",115200,timeout=0.8)
print('serial test start ...')
if ser != None:
print('serial ready...')
else:
print('serial not ready')
sys.exit()
ser.timerout=0.8 #read time out
ser.writeTimeout = 0.8 #write time out.
try:
x = ""
while True:
t = ser.read()
if t != b'':
ser.write(t)
x = x + t
print(str(x)) #<--this one shows what it reads,line by line.
except KeyboardInterrupt:
#print(str(x)) #<--this work fine when I I terminate the loop.
if ser != None:
ser.close()
我希望我捕获的文本看起来像:
123456
更新我的代码后,如果我添加:
try:
x = ""
while True:
t = ser.read()
if t != b'':
ser.write(t)
x = x + t
print(str(x))
except KeyboardInterrupt:
if ser != None:
ser.close()
print(str(x))
我得到这个结果:(我正在从条形码中读取 X001PB45ZF)
X
X0
X00
X001
X001P
X001PB
X001PB4
X001PB45
X001PB45Z
X001PB45ZF
如果我将它添加到循环之外:
try:
x = ""
while True:
t = ser.read()
if t != b'':
ser.write(t)
x = x + t
except KeyboardInterrupt:
print(str(x))
if ser != None:
ser.close()
我得到了这个结果,但只有当我终止程序时。
X001PB45ZF
我将此添加到循环内的代码中:
try:
while True:
t = ser.read()
if t != b'':
ser.write(t)
print(repr(t))
输出现在看起来像这样:
'X'
'0'
'0'
'1'
'P'
'B'
'4'
'5'
'Z'
'F'
'\r'
现在我看到了\r
结尾,我可以终止我的循环,对吗?并根据需要捕获文本?我仍在试图弄清楚如何\r
在扫描仪给出时终止循环......
它现在起作用了!!
try:
x = ""
# look for \r\n. if this doesn't work
# try \x00
while '\r' not in x:
t = ser.read()
if t != b'':
ser.write(t)
x = x + t
x = x.strip() # removes whitepace from beginning and end of string
# including \r \n
print(str(x))
except KeyboardInterrupt:
#print(str(x)) #<--this work fine when I I terminate the loop.
if ser != None:
ser.close()
现在我可以在一行中捕获输入,如何将其添加到无限循环中?
我的目标是读取条形码,将其存储在 txt 或 DB 中。条码处于运动模式,这意味着,一旦相机检测到移动,条码就会激活并尝试读取。
解决方案
尝试在 while 循环完成之前不要打印。
try:
x = ""
while True:
t = ser.read()
if t != b'':
ser.write(t)
x = x + t
#print(str(t))
except KeyboardInterrupt:
print(str(x))
if ser != None:
ser.close()
推荐阅读
- kubernetes - 具有 2 个控制器的 Kubernetes 操作员
- sql - 如何从查找表列中获取一行包含任何
- c# - 为什么 (int)(amount * 100) = 0 当数量 = 0.01 在 C#
- javascript - 如何在 react redux 中添加受保护的路由
- javascript - 排序表无法正常工作
- angular - Angular:不需要 DatePicker 但仍然无效
- c# - 为什么我的列表没有存储我所有的输入?
- c# - 如何禁用树节点复选框?
- stored-procedures - DB2 LUW 版本 10.5.0.10 - 在存储过程中获取警告(未找到)行
- java - IntelliJ 无法识别 Maven 插件