Toggle LED with Button and Arduino

Arduino Experiment: Button to Toggle LED States

Difficulty Level: Beginner

This tutorial demonstrates how to toggle an LED on and off using a push button. The button will act as a switch, and every press will toggle the LED's state (on or off).

Required Components With eBay Links

Wiring

Follow the wiring diagram below to connect the button and LED:

Code Explanation

The code below will toggle the LED's state every time the button is pressed. It uses the digitalRead() function to read the button’s state and the digitalWrite() function to change the LED state.

Arduino Code

Here is the Arduino code to toggle the LED state with a button press:


// Define pins for LED and button
const int buttonPin = 2;     // Pin connected to the button
const int ledPin = 13;       // Pin connected to the LED

// Variables to track LED state and button press
int ledState = LOW;          // Initial LED state is OFF
int buttonState = HIGH;      // Initial button state
int lastButtonState = HIGH;  // Tracks the last button state

void setup() {
  // Set LED pin as output
  pinMode(ledPin, OUTPUT);
  
  // Set button pin as input
  pinMode(buttonPin, INPUT_PULLUP); // Internal pull-up enabled
}

void loop() {
  // Read the current button state
  buttonState = digitalRead(buttonPin);

  // Detect button press (button state goes from HIGH to LOW)
  if (buttonState == LOW && lastButtonState == HIGH) {
    // Toggle the LED state
    ledState = !ledState;
    
    // Write the new state to the LED pin
    digitalWrite(ledPin, ledState);
    
    // Debounce delay to prevent multiple toggles
    delay(50);
  }
  
  // Store the current button state as the last state
  lastButtonState = buttonState;
}
            

Upload and Test

  1. Connect your Arduino to your PC using the USB cable.
  2. Open the Arduino IDE and copy the code above into the editor.
  3. Select your board and the correct port in the IDE.
  4. Upload the code to the Arduino.
  5. Every time you press the button, the LED should toggle between on and off.

Conclusion

In this experiment, you learned how to use a button to toggle the state of an LED. This setup can be extended to other projects where you need to control different devices using buttons.