普中51-单核-A2 STC89C52 Keil uVision V5.29.0.0 PK51 Prof.Developers Kit Version:9.60.0.0 串口示波器:Vofa+ 1.3.10
网上查到的滑动平均值滤波器在计算平均值的时候还要再for累加一遍,这太浪费时间了,在一些性能较拉跨的单片机上是难以接受的。我进行了如下改进:
源码
Filter.c
#include "stdint.h"
#include "Filter.h"
Sliding_Mean_Filter Example_Filter = {{0}, 0, 0, 0};
void Sliding_Mean_Filter_Calc(Sliding_Mean_Filter *filter, double Data)
{
filter->sum -= filter->Filter_Buffer[filter->id];
filter->sum += Data;
filter->Filter_Buffer[filter->id] = Data;
filter->average = filter->sum / Sliding_Mean_Filter_Buffer_Size;
if(++filter->id == Sliding_Mean_Filter_Buffer_Size)
filter->id = 0;
}
Filter.h
#ifndef Filter_H_
#define Filter_H_
#define Sliding_Mean_Filter_Buffer_Size 50
typedef struct
{
double Filter_Buffer[Sliding_Mean_Filter_Buffer_Size];
uint16_t id;
double sum;
double average;
}Sliding_Mean_Filter;
void Sliding_Mean_Filter_Calc(Sliding_Mean_Filter *filter, double Data);
extern Sliding_Mean_Filter Example_Filter;
#endif
使用
Data为喂入的数据,结果在Example_Filter.average里
Sliding_Mean_Filter_Calc(&Example_Filter, Data);
效果
用51单片机测试,晶振频率为11.0592MHz,6T模式,对随机数进行滤波 滤波器的数组大小为50: 可以看到,随机数的均值为0.5,合理! 滤波器的数组大小为10:
滤波器的数组大小为25:
|