Button Controlled LED
Press a button to turn on an LED.
- Beginner
- Input & Controls
- 5 parts
Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.
How it works
A push button connects 5 volts to pin 2. While the button is pressed, pin 2 sees 5 volts and reads high; when it is not pressed, it reads low. The LED on pin 13 (through a resistor, to ground) is the output. On real hardware you would also add a resistor from pin 2 to ground, called a pull-down and usually 10 kΩ, so the pin reads a clean low when the button is open instead of floating.
loop() reads pin 2 with digitalRead() about ten times a second. If it reads HIGH the sketch lights the LED and prints “Button pressed - LED ON”; otherwise it switches the LED off and prints “Button released - LED OFF”. Click and hold the button in the editor while it runs to see the LED follow it.
Parts
- Arduino Uno
- Push Button
- Resistor
- LED
- GND
Wiring
- Arduino Uno 5V → Push Button A
- Push Button B → Arduino Uno D2
- Arduino Uno D13 → Resistor A
- Resistor B → LED Anode (+)
- LED Cathode (-) → GND
Arduino code
// Button Controlled LED
void setup() {
pinMode(2, INPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop() {
int buttonState = digitalRead(2);
if (buttonState == HIGH) {
digitalWrite(13, HIGH);
Serial.println("Button pressed - LED ON");
} else {
digitalWrite(13, LOW);
Serial.println("Button released - LED OFF");
}
delay(100);
}
Try changing it
- Flip the behaviour so the LED is on until you press the button: change buttonState == HIGH to buttonState == LOW.
- Change delay(100) to delay(1000) and notice how sluggish it feels: the sketch only looks at the button once a second.
Next challenge
More projects in Input & Controls
- Potentiometer ReadingRead a potentiometer and display its value on the serial monitor.
- Buzzer AlarmPress and hold the button to sound the alarm buzzer.
- Interrupt Button CounterAn interrupt toggles the LED the instant you press the button, even while loop() is busy…
- Keypad Code LockType a 4-digit code on a keypad and press # to unlock: a servo opens the latch and an…