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 2bool ledState = 0; // Variable to control the state of the ledbool previousState = 0; // Variable to control the previous state of the buttonvoid setup(){pinMode(led, OUTPUT); // led as outputpinMode(button, INPUT);// button as inputdigitalWrite(led, 0); // led off by default}void loop(){bool buttonState = digitalRead(button); // Logical state of the buttonif (buttonState != previousState) { // Debounce implementationif (buttonState == HIGH) ledState = !ledState; // When the button is pressed, change the value of the ledState variable}delay(10); // 10ms pausepreviousState = buttonState; // Debounce implementationdigitalWrite(led, ledState); // The led is turned on or off depending on the value of the variable ledState}
Post a Comment
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.