Python从Arduino读取串行,并跳过第一行读取

时间:2019-01-12 17:20:54

标签: python arduino raspberry-pi

我有一个连接到Raspberry Pi的Arduino,并且正在使用python和串行从Arduino获取数据。我有6个传感器连接到Arduino,但是当我从pi打印数据时,第一行始终是2个或3个传感器,然后将所有6个传感器打印出来。我该如何跳过从序列表读取的第一行?

我的输出如下:

0 2 3
2 4 6 7 8 54
2 3 5 65 7 7
2 3 4 5 6 7

第一行始终少于6个传感器,其值来自数组。因此,如果我要访问arr[4],它将超出范围。

这是python代码。我尝试不使用while循环来执行此操作,我将创建另一个函数,该函数定期调用sensorVals()以更新传感器值。我知道我可以使用循环,检查数组长度为6,然后打印。

import serial
datetime.datetime.now()
ser=serial.Serial('/dev/ttyACM0',115200)
def sensorVals():
    while True:
        read_serial=ser.readline()
        val= read_serial.decode()
        val =val.strip()
        row = [x for x in val.split(' ')]
        if len(row) == 6:
            sensor1 = row[0]
            sensor2 = row[1]
            sensor3 = row[2]
            sensor4 = row[3]
            sensor5 = row[4]
            sensor6 = row[5]
            print (sensor4)
sensorVals()

1 个答案:

答案 0 :(得分:0)

如果您确定只有一行甚至是4个值,这是一种无需循环的方法:

# These lines moved to a new function so we avoid duplication
def readOneSensorLine():
    read_serial=ser.readline()
    val = read_serial.decode()
    val = val.strip()
    return val.split(' ') # You shouldn't need the list comprehension here

def sensorVals():
    row = readOneSensorLine()
    if len(row) == 4:
        # This row is short, so read again
        row = readOneSensorLine()

    return row #or print it, or whatever else needs to be done