filtering pocket values, versus de-bouncing the switches, both have trade offs, if there is a machine with a lot of input switches, pocket filtering is probably a better solution. This little snippet is working well in my applications, it starts a debounce timer and then it uses a rolling average incremented and decremented by the pocket boolean value changing. this works well so far in testing, the variables are adjustable to.
in this configuration, the timer period is 10 msec, and if the switch is false it subtracts from the filter and if the switch is positive is increments the filter, the pocket number change can only be true if for 10 consecutive cycles the switch is either true or false. other wise the output will have to wait until one of them is true and as they can botr change the value from -10 to 0 to 10, it creates a weighted average based in input switch time. Think of it as duty cycle in 10% increments. once the duty cycle is -100% or +100% and the timer is greater than10 fperiod loops, then it updates the pocket number or it doesn't. better than a simple timer, avoids crazy filtering algorithms and solves noisy input problems, needs a watchdog timeout added for the case where the primary timer is greater than 250msec or some type of value , then fault out with a error for switch input noisy etc.
if (PocketFilterFlag == true){ // is flag true to start comparison value count
PocketFilter += fperiod; // set in milliseconds
}
if (pocketunfiltered != pocket){ // set flags and start comparison operator for new pocket value
timer8 = 0;
timer8 += fperiod; // increment timer in milliseconds
PocketFilterFlag = true; // set the flag
}else{
if (pocketunfiltered == pocket){ // cancel if pocket and pockunfiltered are the same and supress timer
timer8 -= fperiod; // flush timer
}
}
if (PocketFilter >= timer8){ // set new pocket value if the pocket value is euqal to or greater than unfiltered for more than 10 milliseconds consecutively
pocket = pocketunfiltered; // set pocket value
PocketFilterFlag = false; // clear flag
timer8 = 0; // flush timer
}