How to Turn an LED On and Off with a Push Button Using Arduino

In this tutorial, we will learn how to control an LED with a push button using Arduino. This is a basic project that is perfect for beginners to get started with Arduino programming and hardware. We will use a push button to toggle an LED on and off.

What You’ll Need:

  • Arduino Board (Arduino Uno, Nano, or any compatible board)
  • LED
  • 220-ohm Resistor
  • Push Button
  • Breadboard
  • Jumper Wires

Circuit Diagram:

  1. LED Connection:
  • Connect the anode (long leg) of the LED to Pin 13 on the Arduino.
  • Connect the cathode (short leg) of the LED to one side of the 220-ohm resistor.
  • The other side of the resistor connects to GND (Ground) on the Arduino.

2. Push Button Connection:

  • Connect one end of the button to Pin 7 on the Arduino.
  • The other end of the button connects to GND.

Arduino Code:

// Pin definitions
const int buttonPin = 7;   // Pin where the button is connected
const int ledPin = 13;      // Pin where the LED is connected

// Variable to hold the button state
int buttonState = 0; 

void setup() {
  // Initialize the button pin as input with internal pull-up resistor
  pinMode(buttonPin, INPUT_PULLUP);
  
  // Initialize the LED pin as output
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // Read the button state (LOW when pressed, HIGH when not pressed)
  buttonState = digitalRead(buttonPin);

  // Check if the button is pressed
  if (buttonState == LOW) {  // Button is pressed when pin is LOW
    // Turn the LED on
    digitalWrite(ledPin, HIGH);
  } else {
    // Turn the LED off
    digitalWrite(ledPin, LOW);
  }
}

How This Code Works:

  • Button Handling: We use the digitalRead() function to read the state of the button. If the button is pressed (button state goes HIGH).
  • LED Control: The digitalWrite() function is used to turn the LED on or off depending on the ledState variable.

Conclusion:

This simple project demonstrates how to control an LED using a push button with Arduino. It’s an excellent starting point for anyone new to electronics and programming with Arduino. Once you’ve mastered this, you can modify the project to work with multiple LEDs or other components to expand your skills.

Feel free to experiment with the code and make changes to suit your needs. Happy coding!