【发布时间】:2020-02-03 20:45:39
【问题描述】:
我正在尝试创建一个循环,每次迭代都会重置其中的所有数据,但即使我在循环内初始化值,数据也不会重置。
这是我的代码:
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 语句中获取字符串,我想知道这是否与问题有关。
【问题讨论】:
-
1) 会不会只在第一个“R”命令时忽略这 4 个字节?
-
2) 确定您阅读了整个回复吗?
-
@tevemadar 是的,因为第一次迭代中的数据是正确的,所以如果传入数据发生变化,我会尝试重新创建它。
-
@tevemadar 是的,可以忽略前几位,因为我只打印收到的数据。
标签: python loops while-loop raspberry-pi serial-communication