How To Make Arduino Button Toggle LED
----------------------------------------------------------------------------------------------------------
Code:
// constants won't change
const int BUTTON_PIN = 7; // Connect the Button to pin 7 or change here
const int LED_PIN = 3; // Connect the LED to pin 3 or change here
// variables will change:
int ledState = LOW; // tracks the current state of LED
int lastButtonState; // the previous state of button
int currentButtonState; // the current state of button
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT); // set arduino pin to input mode
pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode
currentButtonState = digitalRead(BUTTON_PIN);
}
void loop() {
lastButtonState = currentButtonState; // save the last state
currentButtonState = digitalRead(BUTTON_PIN); // read new state
if(lastButtonState == HIGH && currentButtonState == LOW) {
Serial.print("The button is pressed: ");
// toggle state of LED
if(ledState == LOW) {
ledState = HIGH;
Serial.println("Turning LED on");
}
else {
ledState = LOW;
Serial.println("Turning LED off");
}
// control LED arccoding to the toggled state
digitalWrite(LED_PIN, ledState); //turns the LED on or off based on the variable
}
}
---------------------------------------------------------------------------------------------------
Using a button to toggle an LED on the Arduino is a logic game. Our sketch will monitor the button to see if it is pressed, or not pressed. On press, the LED will then toggle On or Off, depending on what state it is currently in. If the LED is on, it will turn off. If it is Off, it will turn On.
Although this simple logic seems overkill (and it is), this is a foundational learning skill that is meant to teach an understanding that can be used for larger, more complicated projects. For example, you might have a whole string of things you need the Arduino to do after pressing the button. It may also need to check sensors and act appropriately!
Imagine a garage door opener for a moment. If you press the button, it doesn’t just open or close the door. Rather it goes through a sequence of logic. Is the door open? If it is open, are the garage door sensors clear of humans or pets? Turn the garage door opener’s internal light on. Begin closing the door. etc.
Before you can do all of those things, you need to learn the basics! So let’s start with simple: Use a button to toggle an LED!