Arduino Basics: Button-Controlled LED
Table of Contents
This project demonstrates how to read a button input and control an LED, introducing you to digital input and output concepts in Arduino.
Hardware Required
- 1 LED
- 1 current-limiting resistor (220–330Ω)
- 1 push button
- Jumper wires and breadboard
- Arduino board (e.g., Uno, Nano)
Wiring
- Connect the LED anode (long leg) to a digital output pin (e.g., pin 13) through a resistor; cathode (short leg) goes to GND.
- Connect one side of the button to a digital input pin (e.g., pin 2).
- Use either:
- An external pull-down resistor to GND, or
- Enable Arduino’s internal pull-up resistor (
INPUT_PULLUP
), connecting the other button leg to GND.
Basic Code: LED ON/OFF
int ledPin = 13; // LED pin
int buttonPin = 2; // Button pin
int buttonState = 0; // Variable to store button state
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
}
void loop() {
buttonState = digitalRead(buttonPin); // Read button
if (buttonState == LOW) { // Button pressed (active low)
digitalWrite(ledPin, HIGH); // Turn LED on
} else {
digitalWrite(ledPin, LOW); // Turn LED off
}
}
Extensions
- Toggle LED on Each Press: Change the code so that the LED switches state every time the button is pressed instead of staying on while pressed. You can use a variable to track the LED state and implement **button debouncing**.
- Multiple Buttons and LEDs: Add more buttons and LEDs using arrays. Each button can control a corresponding LED, which is useful for creating control panels or simple games.
- Combine with PWM: Instead of just ON/OFF, control LED brightness with
analogWrite()
depending on how long the button is pressed or implement dimming effects. - Integrate Sensors: Replace the button with a sensor input (like a light sensor or motion sensor) to automate the LED based on environmental conditions.
Tips
- Always use a resistor with LEDs to prevent damage.
- If using multiple buttons, consider using arrays and loops for cleaner code.
- Test each component individually before combining them in the project.
- Use the Serial Monitor to debug button readings if the LED doesn’t behave as expected.
This simple project teaches the foundation of digital input and output in Arduino and can be expanded in many ways to create interactive systems.
×