python - 在 Loop 中平均实时数据
问题描述
我目前正在通过 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
解决方案
# ...
# 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
# ...
推荐阅读
- reactjs - 如何将分组/嵌套/树数据从材料表导出到 CSV?
- shell - 如何在 shell 脚本中编写用户定义的错误代码
- c++ - Windows 进程句柄数持续增长
- python - 用户没有个人资料。RelatedObjectDoesNotExist
- html - 为什么我在缩放以适应页面 VBA 时会出现空格
- javascript - `Required` 属性不起作用
- amazon-web-services - 组织中的 SCP 限制 EC2 实例的创建,没有强制标签的卷
- swift - 同一应用组中的配套应用和扩展应用的不同路径
- hadoop - Sqoop 导入 Hive - 错误 ("javax.management.MBeanTrustPermission" "register")
- r - 计算不同时间段的平均值