简体   繁体   English

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

[英]Python read serial from Arduino and skip the first line read

I have an Arduino connected to a Raspberry Pi and I am getting the data from the Arduino using python and serial. 我有一个连接到Raspberry Pi的Arduino,并且正在使用python和serial从Arduino获取数据。 I have 6 sensors connected to the Arduino but when I print the data from the pi the first line is always 2 or 3 of the sensors then after that all 6 sensors print out. 我有6个传感器连接到Arduino,但是当我从pi打印数据时,第一行始终是2个或3个传感器,然后将所有6个传感器打印出来。 How would I skip the first line being read over form serial? 我如何跳过从序列表读取的第一行?

My output looks like this: 我的输出如下所示:

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

First line is always less than 6 sensors and the values come from an array. 第一行始终少于6个传感器,其值来自数组。 So if I were to access arr[4] it would be out of bounds. 因此,如果我要访问arr[4] ,它将超出范围。

Here is the python code. 这是python代码。 I am trying to do this without using a while loop, I will be creating another function that calls sensorVals() periodically to update the sensor values. 我尝试不使用while循环来执行此操作,我将创建另一个函数,该函数定期调用sensorVals()以更新传感器值。 I know I can use a loop, check the array length to be 6 then print. 我知道我可以使用循环,检查数组长度为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()

Here's a way without needing a loop, if you're sure that only one line will even be 4 values long: 如果您确定只有一行甚至是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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM