#10Beginner

Led Burning with Button (On Off)

4.8(100)
158 completed
Led Burning with Button (On Off)
A toggle project that changes the state of the LED (on/off) with each button press. Teaches state variable and debounce logic.

Video

Circuit Diagram

Led Burning with Button (On Off) - Circuit

Source Code

Arduino (C++)
1int ledState = 0;
2
3void setup() {
4  pinMode(13, INPUT);
5  pinMode(7, OUTPUT);
6}
7
8void loop() {  
9  if (digitalRead(13) == 1) {
10    ledState = !ledState;
11    digitalWrite(7, ledState);
12    delay(300);
13  }   
14}

FAQ

What is debounce, and why is it necessary?▾

When a mechanical button is pressed, it opens and closes multiple times over the course of a few milliseconds (bouncing). The Arduino may interpret this as multiple presses, and the LED remains in a random state. Debounce ignores this bouncing by waiting a short time (e.g., 50 ms) after a state change.

Sometimes the LED doesn't change, or it changes twice—why?▾

Generally, the debounce is either missing or too short. Additionally, you only need to detect the moment the button is "pressed" (previous state: LOW, new state: HIGH); if the state changes in every cycle while the button is held down, the LED will flicker and remain in a random state.

What is the purpose of a state variable?▾

It keeps track of whether the LED is on or off. With each valid press, the variable is inverted (ledStatus = !ledStatus), and the LED is set accordingly.

Can I control different LEDs using multiple buttons?▾

Yes, it's enough to keep a separate pin, a separate previous state, and a separate LED state variable for each button. If you're using a lot of buttons, arrays and millis()-based debounce code will be more organized.

Led Burning with Button (On Off) | BlueGrays