Push button with LED

Introduction

In this guide, you will learn to combine a with a making a circuit that turns on the LED when the button is pressed down.

Before continuing this guide it is recommended that you have read- or have basic knowledge about and .

Supplies

Circuit

The Arduino circuit created in TinkerCAD
This circuit looks similar to the one that was done in the guide but with a LED added separately. Let's start by connecting the button to the circuit: Connect three wires to the board. Two of these wires should connect the 5 volts (5V) and ground (GND) to one side of the button. Now insert a 10k Ohm resistor in the connection between the button and the wire that goes to the ground. The third wire should be connected to one of the legs on the other side of the button, to one of the pins on the board. This will be the wire that reads if the button is pushed or not. Next, let's connect a LED to the circuit: Start by connecting a wire from a pin to the positive side of the LED. Then from the negative side, connect a 220 Ohm resister from the LED to the ground. When you are finished your circuit should look similar to the picture above.

Code

// Push button with LED
// constants will not change value
const int buttonPin = 2; // a pin is assigned to the button
const int LEDPin = 4;    // a pin is assigned to the LED

// variables will change

// a variable is assigned to read the status of the button
int buttonState = 0;
// a variable is assigned to set the status of the LED
int LEDState = 0;

void setup() {
  // initialize the pushbutton as an input
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output
  pinMode(LEDPin, OUTPUT);
}

void loop() {
  // read state of button value. If the read is 'HIGH' the
  // button is being pushed. If not the value will be 'LOW'
  buttonState = digitalRead(buttonPin);

  // check if the button is pressed.
  if (buttonState == HIGH) {
    // turns on the LED if button is pressed
    digitalWrite(LEDPin, HIGH);
  } else {
    // turns off LED if button is not pressed
    digitalWrite(LEDPin, LOW);
  }
  // adds 1/20 second delay to the program
  delay(50);
}

Challenges

Now that you have completed this guide on how to combine a LED with a push button, you can try to change your button circuit to light up one of three different LED’s at a time, every time you press the button. Only one LED should light up at a time. That way you cycle through all three colours with three button presses.