Hardware Reference
In-Depth Information
shows. However, the button actually bounces up and down before settling, as
the graph on the right shows.
If you know that the switch is going to do this, it is relatively straightforward
to deal with it in software. Next, you write switch-debouncing software that
looks for a button state change, waits for the bouncing to finish, and then reads
the switch state again. This program logic can be expressed as follows:
1. Store a previous button state and a current button state (initialized
to LOW ).
2. Read the current button state.
3. If the current button state differs from the previous button state, wait 5ms
because the button must have changed state.
4. After 5ms, reread the button state and use that as the current button state.
5. If the previous button state was low, and the current button state is high,
toggle the LED state.
6. Set the previous button state to the current button state.
7. Return to step 2.
This is a perfect opportunity to explore using functions for the first time.
Functions are blocks of code that can accept input arguments, execute code
based on those arguments, and optionally return a result. Without realizing it,
you've already been using predefined functions throughout your programs. For
example, digitalWrite() is a function that accepts a pin and a state, and writes
that state to the given pin. To simplify your program, you can define your own
functions to encapsulate actions that you do over and over again.
Within the program flow (listed in the preceding steps) is a series of repeat-
ing steps that need to be applied to changing variable values. Because you'll
want to repeatedly debounce the switch value, it's useful to define the steps for
debouncing as a function that can be called each time. This function will accept
the previous button state as an input and outputs the current debounced button
state. The following program accomplishes the preceding steps and switches
the LED state every time the button is pressed. You'll use the same circuit as
the previous example for this. Try loading it onto your Arduino and see how
it works (see Listing 2-5).
Listing 2-5: Debounced Button Toggling—debounce.ino
const int LED=9; //The LED is connected to pin 9
const int BUTTON=2; //The Button is connected to pin 2
boolean lastButton = LOW; //Variable containing the previous
//button state
boolean currentButton = LOW; //Variable containing the current
//button state
Search WWH ::




Custom Search