Hardware Reference
In-Depth Information
Consider the function definition in the preceding code:
boolean debounce(boolean
last)
. This function accepts a Boolean (a data type that has only two states: true/
false, high/low, on/off, 1/0) input variable called
last
and returns a Boolean
value representing the current debounced pin value. This function compares
the current button state with the previous (
last
) button state that was passed
to it as an argument. The
!=
represents inequality and is used to compare the
present and previous button values in the
if
statement. If they differ, then the
button must have been pressed and the
if
statement will execute its contents.
The
if
statement waits 5ms before checking the button state again. This 5ms
gives sufficient time for the button to stop bouncing. The button is then checked
again to ascertain its stable value. As you learned earlier, functions can optionally
return values. In the case of this function, the
return current
statement returns
the value of the
current
Boolean variable when the function is called.
current
is a
local
variable—it is declared and used only within the debounce function.
When the debounce function is called from the main loop, the returned value
is written to the
global
currentButton
variable that was defined at the top of the
sketch. Because the function was defined as
debounce
, you can call the function
by writing
currentButton = debounce(lastButton)
from within the
setup
or
loop
functions.
currentButton
will be set equal to the value that is returned by
the
debounce
function.
After you've called the function and populated the
currentButton
variable,
you can easily compare it to the previous button state by using the
if
statement
in the code. The
&&
is a logical operator that means “AND”. By joining two or
more equality statements with an
&&
in an
if
statement, you are indicating
that the contents of the
if
statement block should execute only if both of the
equalities evaluate to
true
. If the button was previously
LOW
, and is now
HIGH
,
you can assume that the button has been pressed, and you can invert the value
of the
ledOn
variable. By putting an
!
in front of the
ledOn
variable, you reset
the variable to the opposite of whatever it currently is. The loop is finished off
by updating the previous button variable and writing the updated LED state.
This code should change the LED state each time the button is pressed. If
you try to accomplish the same thing without debouncing the button, you will
find the results unpredictable, with the LED sometimes working as expected
and sometimes not.
BuildingaControllableRGBLEDNightlight
In this chapter, you have learned how to control digital outputs, how to read
debounced buttons, and how to use PWM to change LED brightness. Using
those skills, you can now hook up an RGB LED and a debounced button to cycle
Search WWH ::
Custom Search