Learn Arduino Basics – Turning on LED with Button

Watch “Luna’s wrestling partner for the day” on YouTube
May 13, 2013
Using a Headcollar to walk Your Dog
May 15, 2013
Show all

The code below is a simple script that will allow you to turn an LED on and off with a button. I am using the Arduino Uno, Breadboard, LED, button, 10ohm resistor, 3 wires, and a USB cable to power the Arduino.

It’s a pretty simple setup and I will soon explain why it’s setup this way. For now, feel free to follow the images for the inputs and code to activate the button which will function to turn the LED on and off.

Feel free to comment if you have any questions or improvements to my code or setup.

// Turn on an LED when a button is pushed and keep it on after it's released.

const int LED = 13; // Create a Constant for the Pin which Activated the LED

const int BUTTON = 7; // The input pin where the button is located to turn the LED on and off

int val = 0; // value that stores the state of the input pin

int old_val = 0; // variable that stores the previous state of val

int state = 0; // 0 means that the LED is off and 1 means that the LED is turned on (LIKE YOUR MOM)

void setup() {
pinMode(LED, OUTPUT); // tell arduino that the LED is an output
pinMode(BUTTON, INPUT); // and the BUTTON is an input

void loop(){
val = digitalRead(BUTTON); // read input value and store it

// check if there is any transition
if ((val == HIGH) && (old_val == LOW)) {
state = 1 - state;

old_val = val; // val is now old, so store it

if (state == 1){
digitalWrite(LED, HIGH); // turn LED on
digitalWrite(LED, LOW); // or else turn it off

Dro Simoes
Dro Simoes
Hi! My name is Dro Simoes but people generally call me "The Dro". I'm the bassist for Deadstar Assembly and I also make videos on my youtube channel. I'm a huge fan of wildlife, programming, music, art and much more!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.