Need help understanding a moving average code

I used an averaging code I found online for my ECG filter, the code works better than the one I have, I am wondering why they subtract the last entry. Wouldn't that mean every time a value is added it is immediately subtracted in the next entry?

Normally you would simply add all 10 readings and divide by 10.
Here the programmer subtracts the reading that was made 10 measurements ago and then adds the new measurement to the total of 10 readings...
He also replaces the value of 10 measurements ago with the new value in a circular buffer.
This will be faster especially if you make the buffer longer.
Making it 8 or 16 readings and divide by 8 or 16 would also save you some time (as the compiler will use bitshifts).
The rounding is incorrect in the presented algorithm. 5 should be added to the total before division.

they subtract the reading at readIndex, replace it with a new sample and then advance readIndex so it will be the next sample in readings[] that is replaced

you might also consider leaky integration

float     avg;
int       samp;
const int N = 8;

    avg += (samp - avg) / N;

it's a 1st order low pass filter. the value of avg will approach the value of samp after 3N iterations.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.