Working with “Bouncy” Buttons
When was the last time you had to hold a button down to keep a light on?Probably never. It makes more sense to be able to click the button once to turn iton and to click the button again to turn it off. This way, you do not have to holdthe button down to keep the light on. Unfortunately, this is not quite as easy asyou might first guess. You cannot just look for the value of the switch to changefrom low to high; you need to worry about a phenomenon called switch bouncing.
If you know that the switch is going to do this, it is relatively straightforward
to deal with it in software.
Next, you write switch-debouncing software that
looks for a button state change, waits for the bouncing to finish, and then reads
the switch state again.
This program logic can be expressed as follows:
1. Store a previous button state and a current button state (initialized
2. Read the current button state.
3. If the current button state differs from the previous button state, wait 5ms
because the button must have changed state.
4. After 5ms, reread the button state and use that as the current button state.
5. If the previous button state was low, and the current button state is high,
toggle the LED state.
6. Set the previous button state to the current button state.
7. Return to step 2.