I like this method the best (personal preference) for smoothing signals:
//In setup
int bufferedVal = analogRead(A0);
int unbufferedVal = analogRead(A0);
#define _TOLERANCE_ 5
//The loop
unbufferedVal = analogRead(A0);
if(abs(unbufferedVal - bufferedVal) >= _TOLERANCE_ ) {
bufferedVal = unbufferedVal;
}
This finds the error using the abs()
function (absolute value; makes sure it is positive).
Another thing you can do is round it to the tenth placeholder (i.e. 88 -> 90, 83 -> 80) so it always is a good number to work with:
int val = analogRead(A0);
val += 5;
val = val / 10;
val = val * 10;
The last two lines work because of the lack of precision that integers offer with decimals. If I divide 88 by 10, it doesn't output 8.8; it outputs 8 instead. We then multiply by ten again so it isn't 8 when it really should be 80. The only problem with this is it only rounds down. We can fix this by adding 5 (the halfway point between 10 and 0). That way, it goes: 88 to 93 to 9.3 to 9 to 90.
NOTE: I'm not sure if the compiler will notice the redundancy of the last two lines. If it acts weird, try using the volatile
keyword.