▷ Turn On/Off LED with Button - Arduino

In this post, I will show you how to turn a LED on and off with a button using Arduino. I will guide you step by step so you can understand the basic concepts of electronics and programming in a simple way.

Materials:

Connection diagram.

Explained code:

/*

* Code written by: Esteban Carrillo for EDEPTEC.
* Website: https://www.edeptec.com
* Facebook: @edeptec
* Youtube: https://youtube.com/c/EDEPTEC

*/

#define led 13 // led on pin 13
#define button 2 // button on pin 2

bool ledState = 0; // Variable to control the state of the led
bool previousState = 0; // Variable to control the previous state of the button

void setup()
{
  pinMode(led, OUTPUT); // led as output
  pinMode(button, INPUT);// button as input
  digitalWrite(led, 0); // led off by default
}

void loop()
{
  bool buttonState = digitalRead(button); // Logical state of the button
  if (buttonState != previousState) { // Debounce implementation
    if (buttonState == HIGH) ledState = !ledState; // When the button is pressed, change the value of the ledState variable
  }

  delay(10); // 10ms pause

previousState = buttonState; // Debounce implementation
 
  digitalWrite(led, ledState); // The led is turned on or off depending on the value of the variable ledState
}

0/Leave a comment/Comments

Hello! We're so glad you've made it this far and are reading this article on Edeptec.

This form is an open space for you: you can leave a comment with your questions, suggestions, experiences, or simply your opinion on the topic discussed.

» Did you find the information helpful?
» Do you have any personal experiences you'd like to share?
» Do you have any topics you'd like to see covered in future articles?

Remember that this space is for learning and sharing, so we encourage you to participate respectfully and constructively. Your comments can help other readers who are on the same path, whether in electronics, programming, sports, or technology.

Thank you for being part of this learning community! Your participation is what makes this project grow.