Hardware Reference
In-Depth Information
boolean ledOn = false; //The present state of the LED (on/off)
void setup()
{
pinMode (LED, OUTPUT); //Set the LED pin as an output
pinMode (BUTTON, INPUT); //Set button as input (not required)
}
/*
* Debouncing Function
* Pass it the previous button state,
* and get back the current debounced button state.
*/
boolean debounce(boolean last)
{
boolean current = digitalRead(BUTTON); //Read the button state
if (last != current) //if it's different…
{
delay(5); //wait 5ms
current = digitalRead(BUTTON); //read it again
return current; //return the current value
}
void loop()
{
currentButton = debounce(lastButton); //read deboucned state
if (lastButton == LOW && currentButton == HIGH) //if it was pressed...
{
ledOn = !ledOn; //toggle the LED value
}
lastButton = currentButton; //reset button value
digitalWrite(LED, ledOn); //change the LED state
}
Now, break down the code in Listing 2-5. First, constant values are defined
for the pins connected to the button and LED. Next, three Boolean variables are
declared. When the const qualifier is not placed before a variable declaration,
you are indicating that this variable can change within the program. By defin-
ing these values at the top of the program, you are declaring them as global
variables that can be used and changed by any function within this sketch.
The three Boolean variables declared at the top of this sketch are initialized as
well, meaning that they have been set to an initial value ( LOW , LOW , and false
respectively). Later in the program, the values of these variables can be changed
with an assignment operator (a single equals sign: = ).
Search WWH ::




Custom Search