Jen writes in:
I’m making a circuit to blink an LED at different speeds, that I can control using a button switch. It wouldn’t work until I added added some ‘debounce’ code. What does that mean, and why did I have to add it?
Good Question! Switch bounce is one of those rare electronic effects that is actually caused by a mechanical shortcoming. The issue is in the way the switch works. When you flip a switch (or press down on a button), you’re really pushing one piece of metal against another. If this happens with sufficient force, one or both of the pieces will deform slightly, and then bounce back in the other direction. Depending on how well the switch was designed, this could go on for a number of times before both pieces stop moving. Now, all of this bouncing means that from an electrical perspective, the switch looks like it is opening and closing rapidly until the bouncing dies down. It happens very quickly, however digital electronics are fast enough to see this as a bunch of switch presses!
There are three ways to deal with this: mechanically (building a better switch), electrically (building a filter out of discrete electric components), or digitally (with software).
In your question, you mentioned that you used some debounce code, which is probably the best solution for you. For this solution, you write a software routine that runs when someone presses a button, then waits for a short time (long enough for the bouncing to have stopped) before reading the switch state. This effectively ignores any spurious signals from the switch contacts bouncing without any extra hardware. If you happen to be using the Arduino platform, try this tutorial.
If you aren’t using a microcontroller, though, software isn’t going to help, and you will have to try one of the other solutions. The traditional way to handle switch bounce on a breadboard is to use a resistor-capacitor (RC) filter in a low pass configuration. What this does is prevent the output of the switch from going high too quickly, which effectively filters out any high-speed signals. Check out this tutorial if you’d like to try out this method.
So, how could you re-design the switch to prevent bounce? It turns out that the most common thing to do is to wet the contacts with mercury. Because mercury is a liquid at room temperature, its surface tension keeps the contacts connected even when they bounce. The only issue with this is that mercury is pretty toxic, so you should only use this if you absolutely need to, such as when you’re controlling high-power machines at fast speeds.
[photo by Flickr user russ_j_taylor]