Digital noise filtering by use of Simple Moving Average (SMA)After anti aliasing analog filter and ADC conversion we do end up with a digitized signal.
Read or see more here. A standard simple moving averaging is described in a second source - I prefer the first one The moving average is the most common filter in DSP, mainly because it is the easiest digital filter to understand and use. In spite of its simplicity, the moving average filter is optimal for
a common task:
This makes it the premier filter for time domain encoded signals. However, the moving average is the worst filter
for frequency domain encoded signals,
Relatives of the moving average filter include the Gaussian, Blackman, and multiple- pass moving average. These have slightly better performance in the frequency domain, at the expense of increased computation time. From an implementation view it is convenient that sample frequency has not to be considered and be a part of the filtering algorithm. The filter can be run in realtime on sampled data where the i'th value may be calculated as:
From the litt above:
Higher order gives more efficient filtering but do also by nature has an impact on rapid changes like a step response. From this page the figure below is borrowed where we can see how a stepresponse if flattened out by a 15 sample long averaging filter. The step response takes 15 samples to stabilize - as predicted.
Still - a moving average filter can with succes be used in many cases and is easy to implement. Multiple filteringA way to obtain better filtering is by multiple passes on your data with the SMA algorithm. The following figures are from https://motorbehaviour.wordpress.com/2011/06/11/moving-average-filters/ Situation
IN the multipass invariant we can see that using a 8 sample long SMA and apply it several times (1,2,4) you will get the following.
An exampleIn the figure below a noisy squarewave signal is filtered by a 11 and a 51 point SMA. The result is
I would prefere somthing between 11 and 51 pins. NOTE: that by just looking at the 51 pins it looks like an off line non realtime filtering. This can be seen that from about 180 sample number the 51 pin filtering starts going from 0 to 1 in value. In a(original) we see that it starts going from 0 to 1 at sample nr 200. So if we are doing SAM in realtime we would in fig c see a delay before the signal starts rinsing about …. 51 samples. So use as short as possible SMAs
Some code (no guarantee :-)
#define NRPINS 5
int dataAr[NRPINS];
int dataIndex=0;
int dataSum = 0;
void initSMA()
{
for (int i = 0; i < NRPINS; i++)
{
dataAr[i] = 0;
}
}
int calcSMA(int newSample)
{
dataSum -= dataAr[dataIndex];
dataSum += newSample;
dataAr[dataIndex] = newSample;
dataIndex++;
dataIndex %=NRPINS;
return dataSum/NRPINS;
}
int main()
{
int filterV;
while (1) {
// wait on right time to sample
filterV = calcSMA(readAnalogPort(123));
// do something :-)
}
}
For the interested people some links
|