I have following C++ implementation of the moving average digital filter.
template<uint32_t WINDOW_SIZE>
class MovingAverage{
public:
MovingAverage(){
for(uint32_t elem = 0; elem < WINDOW_SIZE; elem++){
buffer[elem] = 0;
}
input_value = 0;
sum = 0;
average = 0;
index = 0;
}
void setInput(float input){
input_value = input;
}
void calculate(){
sum -= buffer[index];
buffer[index] = input_value;
sum += buffer[index];
average = sum/WINDOW_SIZE;
index = (index + 1) % WINDOW_SIZE;
}
float getOutput(){
return average;
}
private:
float buffer[WINDOW_SIZE];
float input_value;
float sum;
float average;
uint32_t index;
};
I have encountered a weird behavior on the ARM Cortex A9 platform. In case I at first pass the values coming from the adc (those values fluctuates about 514) into the moving average with window size equal to 32 samples and then I force the value 128 to the filter then the filter outputs value about 126 instead of 128. At this moment the buffer
contains value 128 in all its items but the sum
contains different value than the expected 32*128
.
In case I run the filter algorithm on my PC it works as expected. Does anybody have any idea what could be the reason of this behavior?
sum
is wrong, it will stay wrong forever since you always add and subtract the same value. If it runs fine on a PC the problem is probably not in the code you posted, but in the test harness around it $\endgroup$