Arduino: How to turn on an LED with a Push-button

Materials you will need:

  • LED
  • push-button
  • arduino board

//Turns LED on when button is pressed
const int LED=13; // LED is connected to pin 13
const int button=7; // button is connected to pin 7

int val=0; //val stores state of button
void setup()

{
pinMode (LED, OUTPUT);// LED is an output
pinMode (button, INPUT); // button is an input
}

void loop() {
val = digitalRead(button); //read input value and store it
if (val==HIGH) {
digitalWrite (LED, HIGH);
}

else {
digitalWrite (LED, LOW);
}
}

How the code works

The first part of the code defines the variables and gives them their values. Notice how the variable val does not have the word const at the beginning. This is because the value can change. If the button isn’t pressed, it is zero. If the button is pressed, it is one.

The second part of the code defines the variables as inputs or outputs.

 

The last part of the code is where the action happens. It is in a loop, which means it does not stop.

The first line says val = digitalRead(button). When it reads this, it reads the value of the button and stores it.

The second line says if val = HIGH. When the arduino board reads this, it checks the value of the button. If it is high, it will do whatever is in the brackets.

In the brackets it says digitalWrite LED, HIGH. This means the LED turns on.

The else procedure also has in brackets, digitalWrite LED, LOW. This means that if the value is not HIGH, the LED will turn off.

 

The picture below shows how to set up the button and LED.

 

IMG_9166[1]

 

 

 

 

 

 

 

 

 

 

 

IMG_9171[1]

 

 

 

 

 

 

 

 

 

 

 

IMG_9180[1]

 

 

 

 

 

 

 

 

 

 

Put the button in between the divider on the breadboard.

Put one edge of the resistor on the same horizontal line as the right side of the button. Put the other edge anywhere else.

Attach the long side of the LED to pin 13 and the short side on GND (Ground).

Attach one end of a wire to the horizontal line that is the same as where the left side of the button is connected to. The other end goes to 5v.

Attach another wire on the same horizontal line as the left of the resistor and the right of the pushbutton. The other end goes to pin 7, because the value of the button is 7.

Attach a third wire on the same horizontal line on the breadboard as the right of the resistor is at. The other end goes to the Ground next to the 5v pin.

 

1 Comment on Arduino: How to turn on an LED with a Push-button

  1. I like this web site so much, saved to bookmarks.

Leave a comment