You may have noticed that sometimes when you press your button once your program acts as if it has been pressed two or three times. This might be particularly true for your "Interesting Pushbutton". Turns out this is not a software (sketch) problem, but actually a mechanical problem.

Inside the little tactile switch is a small disc spring. When you push the button you squeeze the spring so that it makes contact with the two wire connections. When you release, the spring bounces back. This works great except that, well, the spring is springy. And that means that once in a while, when you press the button it bounces around a little in the switch, making and breaking contact a few times before settling.

If you have a oscilloscope, you can look at the input to the Arduino pin in detail to see the "bouncing" in action. Here is a screencapture from a Tektronix scope

The X axis is time. Each dotted line lengthwise indicates 250 microseconds (.25 milliseconds) The Y axis is voltage. The center is 0 volts (ground) and each dotted line indicates a change of 2V.

In this image you can see how when the button is released, the voltage into the input pin starts at ground (LOW), then there are some spikes and finally it goes up to 5V (HIGH). Most of the time, there are no spikes, but once in a while they do occur. This is called a contact bounce!

Remember! The bounces don't occur when the button is held down or not pressed. They only occur during the press or release of a button.

This causes our sketch to hiccup because every once in a while, there's a bounced switch, and when the Arduino checks the pin it thinks that the user pressed and depressed the switch many times. Thus the light turns on for a few microseconds, and then turns off.

How to solve this problem? Well there are some very fancy techniques one can use to debounce a button but there's also a dead-simple one: adding a delay.

You'll notice that the bounces only occur for half a millisecond. That means that we can check the button twice, at least 1 millisecond apart. If the two readings are different, that means there could have been a bounce. If the two readings are the same, that means that the switch has settled on the value. We'll require that the two readings must read the same before we perform the rest of the sketch. We'll also use a much more generous 10 millisecond delay, which will take care of even the most bouncy of switches.

This is a code snippet you can use to debounce a switch. Add this to your "True Toggle" code and make it work.

val = digitalRead(switchPin); // read input value and store it in valdelay(10); // 10 milliseconds is a good amount of time
val2 = digitalRead(switchPin); // read the input again to check for bouncesif (val == val2) { // make sure we got 2 consistent readings!