Skip to content

Instantly share code, notes, and snippets.

@rioki
Created May 14, 2013
Embed
What would you like to do?
Sliding Average for Boolean Inputs
/**
Sliding Average for Boolean Inputs
Imagine you have a microcorntoler that can only do basic interger arithmetic.
You want to ensure an input does not bounce. Normally you would use floating
point and division to maintain a sliding average, but we neither have
floating point values nore division on the given microcontoler.
So intead a 8 bit integer is used as an average. If the input is up the
average is incremented and if the input id down decremented. To prevent
bounces at around half a basic hysteresis is aded.
Now this function needs to be called over and over to gather and output the
current value. It may be usefull to tune the range of the average and
hysteresis to adjust your required timings.
**/
BOOL in;
BOOL out;
BYTE avg;
void slavg()
{
if (in == 1 && avg != 255)
avg++;
if (in == 0 && avg != 0)
avg--;
if (out == 1 && avg < 75)
out = 0;
if (out == 0 && avg > 180)
out = 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment