我目前正在通过python中的串行端口使用接近传感器。
我得到的数据对应于一个距离。我的目标是获取每4个数据并计算平均值。我很难为此提出一个算法。我正在使用以下代码:
ser = serial.Serial(port = "COM5", baudrate = 230400, bytesize =
serial.EIGHTBITS, parity= serial.PARITY_NONE, timeout = 1)
try:
ser.isOpen()
print("serial Port is open")
except:
print("error")
exit()
if (ser.isOpen()):
try:
while True:
line = ser.readline()
for position, data in enumerate(line):
if position == 4:
print (data)
#while position == 4:
#seq.append(data)
#if len(seq) != 4:
#seq.append(data)
#print (seq)
#while len(seq) == 4:
# print(seq)
# break
###
#if len(seq) != 4:
# seq.append(data)
# print(seq)
# while len(seq) == 4:
# print(seq)
except Exception:
print( "Keyboard Interrupt")
else:
print("cannnot open port")
实际输出如图所示:
要提供一个具体示例,请从以下输出中获取
:23
27
23
45
我想将其格式化为:
29.5
答案 0 :(得分:0)
# ...
# init your List
seq = []
# ...
while True:
# append to your List
seq.append(line[4]) # short for for ... enumerate(line) + if position==4 ... data
# check length of your List
while len(seq)>4:
# reduce length of your List
del seq[0]
# (A + B + C + D) / 4
data = sum(seq) / len(seq)
print(data) # print your fluent mean average
# ...