The Button Sketch for the Arduino

This is the first and perhaps most basic of inputs that you can and should learn for your Arduino projects: the modest pushbutton. For this Arduino project, you will need:

An Arduino Uno

A breadboard

A 10k ohm resistor

A pushbutton

An LED

Jump wires

It’s important to note which legs of the pushbutton are connected. In most cases, these small pushbuttons are made to bridge the gap over the center of your breadboard exactly. If they do bridge the gap, the legs are usually split at 90 degrees to the gap (left to right on this diagram).

You can test the legs of a pushbutton with a continuity tester if your multimeter has that function.

You can see that the resistor leading to ground should be connected to the same side as pin 2, and that when the button is pressed, it connects those to the 5V pin. This setup is used to compare ground (0V) to a voltage (5V) so that you can tell whether the switch is open or closed.

Build the circuit and upload the code from File→Examples→02.Digital→Button.

/*
Button
Turns on and off a light emitting diode(LED) connected to digital
pin 13, when pressing a pushbutton attached to pin 2.
The circuit:
* LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* Note: on most Arduinos there is already an LED on the board
attached to pin 13.
created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Button
*/
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}

After you upload the sketch, give your button a press and you should see the pin 13 LED light up. You can add a bigger LED to your Arduino board between pin 13 and GND to make it easier to see.

If you don’t see anything lighting up, you should double-check your wiring:

Make sure that your button is connected to the correct pin number.

If you are using an additional LED, check that it is correctly situated, with the long leg in pin 13 and the short leg in GND. You can also remove it and monitor the LED mounted on the board (marked L) instead.

Check the connections on the breadboard. If the jump wires or components are not connected using the correct rows in the breadboard, they will not work.