Hello everyone
I am using an exponential moving average to smooth the readings from an LSM303DLHC compass module and it seems to work. However, I do not understand how it works. Here is the code (reading = raw reading from the module):
To me, the filter: 1) adds the latest value to the headingTotal, 2) adds 2 to headingTotal to give average, 3) subtracts 1 from average if value < 0, 4) subtracts average from headingTotal and finally 5) divides average by 4 to produce the smoothed value. What is the point of adding 2 to headingTotal? How does subtracting 1 from average allow for signed integers?
I have tried going through the maths on the website where the filter came from, but it is too much for my poor head:
https://tttapa.github.io/Pages/Math...nential Moving Average/C++Implementation.html
https://tttapa.github.io/Pages/Math...oving Average/Exponential-Moving-Average.html
Can someone please explain it in simple terms? Thanks.
I am using an exponential moving average to smooth the readings from an LSM303DLHC compass module and it seems to work. However, I do not understand how it works. Here is the code (reading = raw reading from the module):
Code:
uint16_t headingTotal = 0;
uint8_t K = 2;
int16_t headingAvg(int16_t reading)
{
headingTotal += reading;
int16_t average = headingTotal + (1 << (K - 1));
if (reading < 0) {
average -= 1;
}
headingTotal -= average;
return average >> K;
}
To me, the filter: 1) adds the latest value to the headingTotal, 2) adds 2 to headingTotal to give average, 3) subtracts 1 from average if value < 0, 4) subtracts average from headingTotal and finally 5) divides average by 4 to produce the smoothed value. What is the point of adding 2 to headingTotal? How does subtracting 1 from average allow for signed integers?
I have tried going through the maths on the website where the filter came from, but it is too much for my poor head:
https://tttapa.github.io/Pages/Math...nential Moving Average/C++Implementation.html
https://tttapa.github.io/Pages/Math...oving Average/Exponential-Moving-Average.html
Can someone please explain it in simple terms? Thanks.