ArduinoNano Button Example


In this example we'll use a button to turn on the built-in LED on PIN 13.


  • Arduino Board
  • momentary button or switch
  • 10K ohm resistor
  • breadboard
  • a bunch of wires


The button used in this sketch has four pins. Connect a pin of the button to 5V, another pin, that nearest, to a resistor connected to GND of the board.
Finally connect another pin of the button to the digital Pin 2, as shown in figure.

When unpressed, there isn't connection between the two legs of it, so the pin is connected to ground through the pull-down resistor and we read a LOW value.
When the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5 volts and we read a HIGH value.

You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH, and going LOW when the button is pressed.
If so, the behavior of the sketch will be reversed, with the LED normally on and turning off when you press the button.

If you disconnect the digital I/O pin from everything, the LED may blink erratically. This is because the input is "floating" - that is, it will randomly return either HIGH or LOW. That's why you need a pull-up or pull-down resistor in the circuit.




// these two costants are used to define used PINs
const int buttonPin = 2;// the number of the button pin
const int ledPin =  13;// the number of the LED pin

int buttonState = 0;// variable used for reading the button 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 and change turn on/off LED
if (buttonState == HIGH) {     
// turn LED on
digitalWrite(ledPin, HIGH);  
else {
// turn LED off
digitalWrite(ledPin, LOW); 

This is how the Button example is shown on the new Arduino Studio. Check it out!