Turn on a LED using a button with Arduino

Turn On an LED Using a Button With Arduino

In this tutorial, I’m going to show you how to turn on an LED using a button with Arduino. This is a pretty simple project, but you should learn how to do it in the beginning because many other sensors and modules are programmed in exactly the same way.

Required components

For this project, you need the following components:

  • 1 Breadboard
  • 1 Arduino Uno
  • 1 LED
  • 1 resistor (220Ω)
  • 1 resistor (10kΩ)
  • 1 push button
  • 5 wires

Circuit

  • Connect the LED to the breadboard.
  • Put the 220Ω resistor in series across the longest pin of the LED (positive side, anode).
  • Connect a wire from Arduino digital pin 13 to the resistor.
  • Connect a wire to the GND pin of the Arduino to the free pin of the LED.
Turn on a LED using a button with Arduino
  • Put a button on the breadboard.
  • Put the 10kΩ resistor in series across the right pin of the button.
  • Connect a wire to the Arduino’s GND pin at the 10kΩ resistor.
  • Connect a wire to the 5V pin of the Arduino, to the left pin of the button.
  • Finally, connect a wire from digital pin 6 of the Arduino to the right pin of the button.

Sketch

  • Plug Arduino into your computer.
  • Start Arduino IDE.
  • Upload the following code.
int state = 0;

void setup() {
  pinMode(13,OUTPUT);
  pinMode(6,INPUT);
}

void loop() {
  state = digitalRead(6);
  
  if(state == HIGH){
    digitalWrite(13,HIGH);
  }
  
  else {
    digitalWrite(13,LOW);
  }
  
}

We define an integer state variable and assign it an initial value of 0. Within the setup function we configure the Arduino pins, where we set 13 as OUTPUT while 6 as INPUT.

Inside loop function we use digitalRead function to read the value of pin 6, then we check if the button is open or closed. If state variable is HIGH, therefore there is voltage, we turn on the LED by using digitalWrite function, otherwise we turn it off.

After uploading the sketch, if you press the button you should see the led light up.

Conclusion

In this article we have seen how to turn on an LED using a button with Arduino, and how easy it is to create a similar project. It is also possible to make the LED blink through a small change to the code, inserting after digitalWrite(13,HIGH) the function delay(500) and immediately after digitalWrite(13,LOW).

Lorenzo Miscoli

Software Developer specialized in creating and designing web applications. I have always loved technology and dreamed of working in the IT world, to make full use of my creativity and realize my ideas.

You might also like

Scroll to Top