To wire this circuit, we connect one leg of the pushbutton switch to Pin 8 on the ARDUINO board. This same leg of the pushbutton is connected to one leg of a 10K OHM resistor and the other leg of the resistor is connected to +5VDC. The other leg of the switch is connected directly to GROUND. In our code, we will set Pin 8 to be an INPUT and we will continuously scan and read the state of this pin. When the button is at rest in its Normally Open State, Pin 8 is connected to +5VDC through our pull-up resistor. Input 8 is now HIGH and will tell the ARDUINO to leave the LED OFF.
When the Button is pressed, a connection between Pin 8 and GROUND will be made and the Input will be in a LOW State. The connection to +5VDC through the pull-up resistor will be ignored, because electricity will always follow the path of least resistance. Without the use of the pull-up resistor to +5VDC, when the button was not pressed, Input Pin 8 would be in a floating state (neither HIGH nor LOW) and could cause erratic readings of its state.
Connect the Anode (Long Lead) of the LED to Digital Pin 13, with the other lead of the LED connected to a 270 OHM Resistor to Ground.
Code: Select all
// BUTTON: Digital In/Out DEMO
// This example turns an LED connected to PIN 13 on the ARDUINO on when Button
// connected to Pin 8 is pressed and turns off LED when Button is released
int ledPin = 13; // declare variable for Digital Pin LED is connected to
int buttonPin = 8; // declare variable for Digital Pin Button is connected to
int buttonState = 0; // declare variable for reading Input Pin status
void setup(){
pinMode(ledPin, OUTPUT); // sets Digital Pin 13 as an OUTPUT
pinMode(buttonPin, INPUT); // sets Digital Pin 8 as an INPUT
}
void loop()
{
buttonState = digitalRead(buttonPin); // read state of buttonPin
if (buttonState == HIGH) // check if the input is HIGH (button not pressed)
{
digitalWrite(ledPin, LOW); // turn off the LED
}
else // button is pressed and buttonState==LOW
{
digitalWrite(ledPin, HIGH); // turn on the LED
}
}