Arduino到Python:如何使用读写线()放入具有指定起点的列表中?

2024-09-28 05:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个相当具体的问题,所以请接受我。在

我有14个超声波传感器连接到一个Arduino上,将实时读数发送到串行监视器(或者当我插上它的时候是Pi)。读数按如下方式发送,,每两位数字之间有一条新行(Z除外)。在

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

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

当python读取读数时读写线()它没有起点。它可能从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

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

谢谢你


Tags: linerandom传感器arrayarduinoserprint读数
1条回答
网友
1楼 · 发布于 2024-09-28 05:16:18

这个怎么样?请注意,您的支票overallcount<;30和arraycount<;15实际上应该是overallcount<;=30和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

相关问题 更多 >

    热门问题