
Video
Circuit Diagram

Source Code
1// ─────────────────────────────────────────
2// BlueGrays · bluegrays.com
3// Toggle an LED with a Button (On/Off)
4// ─────────────────────────────────────────
5// Each button press toggles the LED (on/off). The 300 ms wait ignores
6// button bounce. If the button is held, the LED toggles every 300 ms.
7//
8// Pins:
9// D13 -> Button, other leg to 5V
10// D13 -> 10k resistor to GND (pull-down)
11// D7 -> LED (with a 330 ohm resistor)
12
13int ledState = 0; // LED state: 0 = off, 1 = on
14
15void setup() {
16 pinMode(13, INPUT); // Button input (external pull-down)
17 pinMode(7, OUTPUT); // LED output
18}
19
20void loop() {
21 if (digitalRead(13) == 1) { // Button pressed
22 ledState = !ledState; // Flip the state
23 digitalWrite(7, ledState);
24 delay(300); // Wait out the bounce
25 }
26}
27FAQ
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.
