缺少来自pyserial的输出

时间:2016-04-05 10:55:37

标签: python pyserial

我正在使用以下代码从串口读取:

z1baudrate = 115200
z1port = '/dev/ttyUSB11'
ser = serial.Serial(z1port, z1baudrate, timeout=0, parity=serial.PARITY_NONE,

                    stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
while True:
    queue = ser.inWaiting()
    if queue > 0:
        data = ser.read(1000)
        print data
    time.sleep(.2)

我应该每隔几秒钟打印一次这个结果

bbbb::0000:0:0:00 2412 7 -1 250 -58 108 0 2398 # output 1 
bbbb::0000:0:0:00 2475 4 1 264 -46 106 1 2423 # output 2

但相反,我偶尔会收到不完整的输出,如

bbbb::0000:0:0:00 # sometimes broken into 2 lines
2412 7 -1 250 -58 108 0 2398 # line 2
bbbb::0000 # sometimes a part of the output is missing like this 
bbbb::0000:0:0:00 2475 4 # or like this. Length is variable!

有什么问题?是同步问题吗?我该如何解决?

1 个答案:

答案 0 :(得分:1)

它是sleep和print语句的组合。程序在收到句子时可能会睡眠,使用print命令时,每次都会写一个新行。

试试这个:

import sys

z1baudrate = 115200
z1port = '/dev/ttyUSB11'
ser = serial.Serial(z1port, z1baudrate, timeout=0, parity=serial.PARITY_NONE,

                    stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
while True:
    data = ser.readline()
    sys.stdout.write(data)