In practice, all mechanical switch contacts bounce (that is, turn on
and off, repeatedly, for a short period of time) after the switch is
closed or opened.
As far as the microcontroller is concerned, each ‘bounce’ is
equivalent to one press and release of an ‘ideal’ switch. Without
appropriate software design, this can give rise to a number of
problems, not least:
• Rather than reading ‘A’ from a keypad, we may read
‘AAAAA’
• Counting the number of times that a switch is pressed
becomes extremely difficult.
• If a switch is depressed once, and then released some time
later, the ‘bounce’ may make it appear as if the switch has
been pressed again (at the time of release).
Creating some simple software to check for a valid switch input is
straightforward:
1. We read the relevant port pin.
2. If we think we have detected a switch depression, we wait for
20 ms and then read the pin again.
3. If the second reading confirms the first reading, we assume
the switch really has been depressed.
Note that the figure of ‘20 ms’ will, of course, depend on the switch
used.