首页 > 解决方案 > 在 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

标签: pythonpython-3.xpyserial

解决方案


# ...
# 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
    # ...

推荐阅读