我尝试从设备中读取每2秒1到3行文本的行到串行打印机,使用pyserial读取该设备的串行输出。
首先,我使用minicom获取输出样本:当我用hax-reader(linux中的ghex)打开它时,我看到行的每一端都有十六进制值x0A。
当我使用pyserial(版本3.2.1)逐字节捕获输出时:
print(self.ser.read())
一行末尾的输出是
B '\ r'
B '\ n'
每次一行结束(为什么两个字符?)
我试图定义一个read_line()函数:
import serial
def read_line(self):
line = []
print("start read_line")
while True:
print("read_line_loop")
for c in self.ser.read():
line.append(c)
print("appended")
if c == b'\x0A':
print("stop condition")
print("Line: " + line)
line = []
break
循环按预期输入,但从不满足条件c == b'\ x0A'。 显示的消息是“read_line_loop”,每隔几秒就会出现几次 “附加”,但从不“停止条件”。
有什么想法吗?
答案 0 :(得分:0)
Ending a line with \r\n (carriage return, line feed) is the normal Windows (and typewriter) method to end a line. Translated in Hex these signs are '\x0D' and '\x0A'. Why it is not found I cannot tell you. But as you are reading lines, I would use the readline method of the serial port. As your line is ending with \n it should work nicely. You only get a problem, when your line is not ending with \n, but with something else.
答案 1 :(得分:0)
One approach would be to output c to see what it actually is. c is likely something different than what you think.
Another approach could be to use the built-in readline method, which uses newline as it de(http://pyserial.readthedocs.io/en/latest/shortintro.html#readline).