代码之家  ›  专栏  ›  技术社区  ›  Ahmed Al-haddad

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

  •  1
  • Ahmed Al-haddad  · 技术社区  · 10 年前

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

    串行端口输出:

    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()
    
    1 回复  |  直到 10 年前
        1
  •  2
  •   Mitchell Chu    10 年前

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

    更新时间:

    使用 picocom -b 115200 /dev/ttyUSB0 或者putty(串行模型)来检测端口和波特率是正确的。我在你的两个问题中有两个不同的端口。如果打开错误端口, 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.