A Switch Debouncing Method
There are a lot of different methods used to debounce switch inputs and this post is just about one method that I read about recently and used a couple of times now. So far it seems pretty good and does the job.
The C code for this method is just below, I defined it as a macro so I can use it for multiple switch inputs. All you need to do is execute this code at a fixed sample rate and it will do the rest.
if( input == OFF ) { if( integrator > 0 ) { integrator--; } } else if( integrator < PERIOD ) { integrator++; } if( integrator == 0 ) { output = OFF; } else if( integrator >= PERIOD ) { output = ON; integrator = PERIOD; }
What this basically does is average samples. When the input is high the “integrator” counts up until it reaches the PERIOD constant. Then it sets the output high and also saturates the integrator to the value of PERIOD. When the input is low the integrator counts down until it reaches 0 when it sets the output low.
I cant remember where I found this method, I believe the link is somewhere on Jack Ganssle’s website. He also has a good tutorial on switch debouncing.
c electronics programming tips