A very common and annoying problem: How can I debounce my buttons? Who doesn’t know this….
I will tell you 3 possible solutions: two hardware and one software solution. Lets begin with the hardware.
This is a simple circuit with a RC-filter and a Schmitt-Trigger inverter. If the button is open (as usual) the capacitor will charge up and the inverter goes low. If you press the button, the capacitor will slowly (slowly in this case: 1ms) discharge. If th ebutton bounces, the RC-filter will not let the voltage go significantly higher, thus filtering out the bounce. The Schmitt-Trigger is important for the hysteresis, so that the output does not oscillate.
The second circuit is a bit different and you need a button with a NC and NO contact (Normally Closed, Normally Opened, simple changing switch).
With two NOR-gates i made a simple RS-flipflop. This flipflop is wired up, that the input of IC1a is held high. Output is low. IC1b has botz inputs low, output is high. Now both inputs of IC1a are high.
Now if you push the button, the input of IC1b becomes high changing the output to low. IC1a has now both inputs low, changing it’s output to high, holding IC1b fixed at low. If the button now bounces, nothing happens, because the input lines are pulled down. The flipflop saves the current value and the button is debounced.
But now comes the software:
You can debounce buttons in software too. In C for example you can test if the button was pressed (simple if-statement) and then set a small delay (e.g. 10ms) to wait until the button stops bouncing. The code might look something like this:
The the if-statement is looking for the first instance the button was pressed and if we already sensed it. This way it doesn’t wait 10ms if the button keeps pressed but proceeds with the code. Since buttons don’t usually bounce more than 10ms, this method is working pretty well. Even though microcontrollers have their own problems, but that’s a topic for later.