Arduino to Python:如何使用 ser.readline() 将读数导入具有指定起点的列表?

Arduino to Python: How to import readings using ser.readline() into a list with a specified starting point?

这是一个非常具体的查询,请耐心等待。

我有 14 个超声波传感器连接到 Arduino 上,将实时读数发送到串行监视器(或插入时的 Pi)。读数按如下方式发送,每 2 位数字之间换行(Z 除外)。

Z 62 61 64 63 64 67 98 70 69 71 90 XX 75 XX

这些测量值以厘米为单位。 “XX”表示读数超出两位数范围。 Z 已被指定为起点,因为 pi 非常快速且重复地读取传感器,大约在一秒内读取 80 个读数。所以 ser.readline() 给出了相同传感器的多个样本

当python读取ser.readline()中的读数时,它没有起点。它可能从 70、XX 或 Z 开始。我想将它分配到一个可访问的列表中,以便:

array [0] = Z (always)

array [1] = 62 (first two digits)

array [2] = 61 (second two digits)

..

array [14] = XX (fourteenth two digits)

这是我的代码,不幸的是它不起作用,因为列表超出范围:

import serial
ser = serial.Serial('/dev/ttyACM0',115200)

print ("Start")

overallcount=1 #initialise 2 counters
arraycount =1
array = [] #initialise 2 lists
line = []

while True:
    while overallcount<30: #read 30 random readings from Arduino
        ser.readline()      
        print(str(overallcount)) #print reading number
        while arraycount<15:     #Number of readings to fill the array to be made
            for line in ser.readline():
                if line == 'Z':         #If element in ser.readline is "Z"
                    array[0] == line    #Assign first list element as Z (starting point)              
                arraycount=arraycount+1 #Iterate through until 14 sensors are read
            arraycount=1                #reset counter
        overallcount=overallcount+1     #Iterate through 30 random Arduino readings
    overallcount=1                      #iterate random counter

如果你能告诉我我做错了什么,或者如果有更好的方法,我将非常感激!

谢谢

这个怎么样?请注意,您的支票 overallcount<30 and arraycount<15 实际上应该是 overallcount<=30 and arraycount<=15.

import serial
ser = serial.Serial('/dev/ttyACM0',115200)

readings = [] # Array to store arrays of readings
reading_id = 1 # Id of current reading
random_lines_expected = 30 # NUmber of random lines
num_sensors = 14 # Number of sensors

def read_random():
    for _ in range(random_lines_expected):
        ser.readline() 

read_random() # Read initial random lines
while True:
    print "Reading #", reading_id
    reading = [] # Initialize an array to collect new reading
    while ser.readline().strip() != 'Z': # Keep reading lines until we find 'Z'
        pass
    reading.append('Z') # Add Z to reading array
    for _ in range(num_sensors): # For 14 sensors...
        reading.append(ser.readline().strip()) # Add their value into array
    readings.append(reading) # Add current reading to the array or readings
    reading_id += 1 # Increment reading ID
    #read_random() #Uncomment this if random follows each series of readings