After initializing the button and LED pins, we declare two variables:
old_but-
ton_state
stores the previous state of our pushbutton, and
led_state
stores the
LED’s current state. Both can be either
HIGH
or
LOW
.
In the
loop
function, we still have to read the current button state, but now
we not only check whether it is
HIGH
, but we also check whether it has changed
since the last time we read it. Only when both conditions are met do we toggle
the LED’s state. So, we no longer turn the LED on and off over and over again
as long as the button is pressed. At the end of our program, we have to store
the button’s current state in
old_button_state
.
Upload the new version, and you’ll see that this solution works much better
than our old one. But you will still find some cases when the button doesn’t
behave fully as expected. Problems mainly occur in the moment you release
the button.
These problems occur because the mechanical buttons bounce for a few
milliseconds when you press them. In the following figure, you can see a
typical signal produced by a mechanical button. Right after you have pressed
the button, it doesn’t emit a clear signal. To overcome this effect, you have
to debounce the button. It’s usually sufficient to wait a short period of time
until the button’s signal stabilizes. Debouncing ensures that the input pin
reacts only once to a push of the button:
Button pressed
Button released
5 V
0 V
In addition to debouncing, we still have to store the current state of the LED
in a variable. Here’s how to do that:
BinaryDice/DebounceButton/DebounceButton.ino
const unsigned int BUTTON_PIN = 7;
Line 1
const unsigned int LED_PIN = 13;
-
void setup() {
-
pinMode(LED_PIN, OUTPUT);
-
pinMode(BUTTON_PIN, INPUT);
5
}
-
-
int old_button_state = LOW;
-
int led_state = LOW;
-
10
void loop() {
-
Chapter 3. Building Binary Dice • 52
report erratum • discuss
www.it-ebooks.info