Use a Push Button with Arduino

Turn an LED on and off with the Arduino

Written By: Cherie Tan

Dash icon
Difficulty
Easy
Steps icon
Steps
8
Push button switches are inexpensive and versatile components that have many uses. 

In this guide, we will learn how to use a push button switch together with an Arduino, to turn an LED on and off. The circuit we will be building, uses a Little Bird Uno R3, a fully compatible Arduino development board. A mini pushbutton switch, a 5mm LED, jumper wires, and a mini breadboard is also required.

Other uses for push buttons are in custom gamepads, DIY radio buttons, MIDI controllers with push buttons that in conjunction with LEDs would light up when pressed, and many more!

Step 1 Insert LED into the Breadboard

Insert an LED into the breadboard with the Anode (positive leg) on the left and the Cathode (negative leg on the right).

Step 2 Insert a 220 ohm resistor

Insert a 220 Ohm Resistor so that one leg is inline with the LED's Cathode leg.

Resistors are not polarised, so orientation doesn't matter.
This resistor will be used to limit the current going to our LED.

Step 3 Insert the button

Insert your push button so that one leg is in line with the other end of the resistor.
Be sure to really push down on the push button so that the bottom of the push button is flush with the breadboard (this will feel like you're pushing too hard).

Step 4 Connect pin 13 to the LED

Connect pin 13 to the anode of the LED.

Step 5 Connect the resistor to ground

Connect the resistor to ground.

Step 6 Connect the push button to pin 7

Connect the push button to pin 7.

Step 7 Program 1: Push to turn on the LED

const int ledPin = 13;// We will use the internal LED
const int buttonPin = 7;// the pin our push button is on

void setup()
{
  pinMode(ledPin,OUTPUT); // Set the LED Pin as an output
  pinMode(buttonPin,INPUT_PULLUP); // Set the Tilt Switch as an input
}

void loop()
{
  int digitalVal = digitalRead(buttonPin); // Take a reading

  if(HIGH == digitalVal)
  {
    digitalWrite(ledPin,LOW); //Turn the LED off
  }
  else
  {
    digitalWrite(ledPin,HIGH);//Turn the LED on
  }
}
Upload this code to your Arduino.
When you run this code, the LED on Pin 13 will turn on when the button is held down. That is all.

Step 8 Program 2: Toggle the LED

const unsigned int buttonPin = 7;
const unsigned int ledPin = 13;

int buttonState = 0;
int oldButtonState = LOW;
int ledState = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  buttonState = digitalRead(buttonPin);

  if (buttonState != oldButtonState &&
      buttonState == HIGH)
  {
    ledState = (ledState == LOW ? HIGH : LOW);
    digitalWrite(ledPin, ledState);
    delay(50);
  }
  oldButtonState = buttonState;
}
Upload this code to your Arduino.
This program will toggle on and off the LED every time you push the button.