Hardware Reference
In-Depth Information
Recall from the previous sidebar on Ohm's law and the power equation that
current will always follow the path of the least resistance in a circuit. In this
scenario, the majority of the current flows through the button, and a high logic
level is generated on the input pin, because that is the path of least resistance.
NOTE Thisexampleusesapulldownresistor,butyoucouldalsouseapullup
resistorbyconnectingtheresistorto5Vinsteadofgroundandbyconnectingthe
othersideofthebuttontoground.Inthissetup,theinputpinreadsahigh-logic
valuewhenthebuttonisunpressedandalow-logicvaluewhenthebuttonisbeing
pressed.
Pulldown and pullup resistors are important because they ensure that the
button does not create a short circuit between 5V and ground when pressed
and that the input pin is never left in a floating state.
Now it is time to write the program for this circuit! In this first example, you
just have the LED stay on while the button is held down, and you have it stay
off while the button is unpressed (see Listing 2-4).
Listing 2-4: Simple LED Control with a Button—led_button.ino
const int LED=9; //The LED is connected to pin 9
const int BUTTON=2; //The Button is connected to pin 2
void setup()
{
pinMode (LED, OUTPUT); //Set the LED pin as an output
pinMode (BUTTON, INPUT); //Set button as input (not required)
}
void loop()
{
if (digitalRead(BUTTON) == LOW)
{
digitalWrite(LED, LOW);
}
else
{
digitalWrite(LED, HIGH);
}
}
Notice here that the code implements some new concepts, including
digitalRead and if / else statements. A new const int statement has been
added for the button pin. Further, this code defines the button pin as an input
in the setup function. This is not explicitly necessary, though, because pins
are inputs by default; it is shown for completeness. digitalRead() reads the
Search WWH ::




Custom Search