Programming Arduino (1) Pages 126
Programming Arduino (1) Pages 126
void loop()
if (digitalRead(inputPin) == LOW)
ledValue = ! ledValue;
digitalWrite(ledPin, ledValue);
delay(500);
By putting a delay here, nothing else can happen for 500 milliseconds, by
which time any bouncing will have subsided. You should find that this makes the
toggling much more reliable. An interesting side-effect is that if you hold the
button down, the LED just keeps flashing.
If that is all there is to the sketch, then this delay is not a problem. However,
if you do more in the loop , then using a delay can be a problem; for example,
the program would be unable to detect the press of any other button during that
500 milliseconds.
So, this approach is sometimes not good enough and you will need to be a bit
more sophisticated. You can write your own advanced debouncing code by hand,
but doing so gets complicated and fortunately some fine folks have done all the
work for you.
To make use of their work, you must add a library to your Arduino