Python - 可用时逐行从串口数据读取到列表中

Python - read from the serial port data line by line into a list when available

我的目标是编写一个代码,它将无限期地监听和读取串行端口,每隔几秒就会产生一次输出

串口输出:

aaaa::abcd:0:0:0
//printf("%d\n",data[0]);
2387
//printf("%d\n",data[1]);
14
-9
244
-44
108

我希望将数据附加到这样的列表中,python 假定输出

[abcd::abcd:0:0:0, 2387, 14, -9, 244, -44, 108]

我在许多其他代码中尝试过此代码,但没有任何效果,我一直没有输出 编辑-下面的代码给了我这个输出

'''[['abcd::', 'abcd::', 'abcd::', 'abcd::', 'abcd::']] #or
[['abcd::abcd:0:0:c9\n', '2406\n', '14\n', '-7\n']] # and so on, different output for each iteration''' 
#[['aaaa::c30c:0:0:c9\n', '2462\n', '11\n', '-9\n', '242\n', '-45\n', '106\n']] apparently it worked only once. 


ser = serial.Serial('/dev/ttyUSB1',115200, timeout=10)
print ser.name
while True:
    data = []
    data.append(ser.readlines())
    print data 
    # further processing 
    # send the data somewhere else etc
print data
ser.close()

readline 将继续读取数据直到读取终止符(新行)。请尝试:read.

更新:

使用picocom -b 115200 /dev/ttyUSB0或putty(串口机型)检测端口,波特率是否正确。我在你的两个 questions.if 打开的错误端口中有两个不同的端口, read() 将一直等待直到读取一个字节。像这样:

import serial
# windows 7
ser = serial.Serial()
ser.port = 'COM1'
ser.open()
ser.read() # COM1 has no data, read keep waiting until read one byte.

如果你在控制台中输入这段代码,控制台不会有这样的输出:

>>> import serial
>>> ser = serial.Serial()
>>> ser.port = 'COM1'
>>> ser.open()
>>> ser.read()
_

我们需要添加读取超时来修复它。
你可以试试这个:

import serial
import time

z1baudrate = 115200
z1port = '/dev/ttyUSB0'  # set the correct port before run it

z1serial = serial.Serial(port=z1port, baudrate=z1baudrate)
z1serial.timeout = 2  # set read timeout
# print z1serial  # debug serial.
print z1serial.is_open  # True for opened
if z1serial.is_open:
    while True:
        size = z1serial.inWaiting()
        if size:
            data = z1serial.read(size)
            print data
        else:
            print 'no data'
        time.sleep(1)
else:
    print 'z1serial not open'
# z1serial.close()  # close z1serial if z1serial is open.