I'm trying to apply an exponential moving average filter to an analog input.
The formula for an EMA filter is as follows:
value = measurementalpha + previous value(1-alpha)
where alpha is some number between 0 and 1.
Because I'd like to avoid floating value math, I've implemented it as shown below, and it works quite well. It allows me to choose alpha values of integers from 1-10.
// GAUGE DATA 2 UPDATE FUNCTION //
int gauge2 () {
int alpha_2 = 1; // smoothing factor (between 0-10)
A8_raw = analogRead(A8); // read analog values from input_8
A8_sm = (A8_raw*alpha_2 + A8_sm*(10-alpha_2))/10; // calculate smoothed value (EMA filter)
int angle = map( A8_sm, 0, 1024, 0, STEPS2); // calculate angle of motor
return angle; // return angle of motor
}
The limitation in the code above is that I can't fine tune the filter with only ten possible values. I'd prefer to chose an integer from 1-100, but when I change the code to allow that (see below), the A8_sm value begins to swing wildly, if A8_raw gets above about 325.
// GAUGE DATA 2 UPDATE FUNCTION //
int gauge2 () {
int alpha_2 = 10; // smoothing factor (between 0-100)
A8_raw = analogRead(A8); // read analog values from input_8
A8_sm = (A8_raw*alpha_2 + A8_sm*(100-alpha_2))/100; // calculate smoothed value (EMA filter)
int angle = map( A8_sm, 0, 1024, 0, STEPS2); // calculate angle of motor
return angle; // return angle of motor
}
What's going on here? This function is used in a code that also has an interrupt every 200 microseconds. My theory is that the division by 100 is taking so long that the interrupt is causing problems with this function, and somehow, division by 10 doesn't take as long... But I really don't know, I'm still pretty new to arduino and weak in programming.