首页 > 解决方案 > 循环执行后列表不重置

问题描述

我正在尝试创建一个循环,每次迭代都会重置其中的所有数据,但是即使我在循环中初始化值,数据也不会在某处重置。

这是我的代码:

import time , sys , string
import serial

ser = serial.Serial("/dev/ttyUSB0", baudrate=9600,
                   parity=serial.PARITY_NONE,
                   stopbits=serial.STOPBITS_ONE,
                   bytesize=serial.EIGHTBITS
                   )
print (ser.name)
ser.write(b'U')
#print ('test1')

time.sleep(2)

b=0
while (b <= 2):

    time.sleep(0.25)

    ser.write(b'R')
    #print ('test2')

    d = [] # establishes an empty list to iterate through all the incoming data
    i=0 # beginning of the buffer
    time.sleep(0.5)

    while (i<=11):
        d.append(str(ord(ser.read()))) #adding each incoming bit to the list
        #print (d[i])
        #print ('^ is the ' + str(i) + 'th term')  // these two lines help establish where the useful information begins for the lidar. 

        i+=1

    #establishing a better way to write the data out / gd = good distance
    gd = []
    a = 0
    for a in range(8):
        gd.append(str(chr(int(d[a+4]))))
    print (gd)

    print (gd[0] + gd[1] + gd[2] + gd[3] + gd[4] + gd[5] + gd[6] + gd[7] + ' mm')

    ser.flush()
    b+=1

我这样做的原因d[a+4]是因为前几位信息是无意义的,所以我每次都需要从那一点开始。

该程序在第一个循环中工作并正确打印出来,但是,在随后的循环中,当我尝试再次打印出值时,它开始从不同的点开始。我不确定我是否遗漏了什么,并且会喜欢第二个意见。

我的输出是:

D = 0609 mm
\r:\rD = 0 mm
mm \r:\rD mm

所以它围绕着我在某处创建的列表循环,因为它从 print 语句中获取字符串,我想知道这是否与问题有关。

标签: pythonloopswhile-loopraspberry-piserial-communication

解决方案


我无法添加评论,所以这里有一个小建议。在主循环结束时,之后

b+=1

添加以下行

d, gd = [], []

如果它们在循环结束后不再有用(我怀疑是这种情况)。它将重置两个变量在其中保存的任何值,您将能够再次从空列表开始。


推荐阅读