Using a push button (switch) to control an LED

In this tutorial, we will use a push-button (switch) to turn an LED light on and off.

You will need the following:

  • Arduino Uno microcontroller board
  • Breadboard
  • LED light
  • Push button
  • Resistor (10K Ohm)
  • Jumper wires (male-to-male)

Wiring schematic

Wire up the LED light and push button to the Arduino Uno using a breadboard and jumper wires as shown below.

pushbutton

The LED’s long pin is connected to Digital Pin 13 on the Arduino and to GND via the breadboard. The push button is connected to Digital Pin 2, GND (via a 10K Ohm resistor) and 5V via the breadboard.

The code

Here is the code:

/*
  Button

  Turns on and off an LED attached to digital pin 13,
  when pressing a push-button that is attached to digital pin 2.

  Wiring:
  - LED attached from pin 13 to ground
  - pushbutton attached to pin 2 from +5V
  - 10K resistor attached to pin 2 from ground

*/

const int buttonPin = 2;     // push button connected to digital pin 2
const int ledPin =  13;      // led connected to digital pin 13

boolean lastButton = LOW;    // last state of the button (on or off)
boolean ledOn = false;       // current state of the led (on or off)
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 && lastButton == LOW) {
    // turn LED on:
    ledOn = !ledOn; // This inverts (switches) the value.
    lastButton = HIGH;
  }
  else {
    lastButton = digitalRead(buttonPin);
  }

  if(ledOn) 
  {
    digitalWrite(ledPin, HIGH);
  }
  else
  {
    digitalWrite(ledPin, LOW);
  }
  delay(50);
}

Now test it out by pressing the push button to turn the LED on, and pushing it again to turn it off. Make sure you press the button firmly and you may need to hold it down briefly.