03 / Templates · beginner
PUSHBUTTON TOGGLE LED
Open in PlaygroundPress the button to toggle a red LED on and off. Uses INPUT_PULLUP so no external resistor is needed on the button — reads HIGH when released, LOW when pressed.
beginnerbuttonLEDdigital inputINPUT_PULLUPtoggle
sketch.inoArduino C++
20 lines
// Pushbutton — toggle an LED on each press
const int BTN = 2;
const int LED = 13;
bool ledState = false;
bool lastBtn = HIGH;
void setup() {
pinMode(BTN, INPUT_PULLUP);
pinMode(LED, OUTPUT);
}
void loop() {
bool btn = digitalRead(BTN);
if (btn == LOW && lastBtn == HIGH) { // falling edge = press
ledState = !ledState;
digitalWrite(LED, ledState);
delay(20); // debounce
}
lastBtn = btn;
}- Arduino Uno01
- Pushbutton (wokwi-pushbutton)02
- LED (red)03
- Resistor 220Ω04
| Component Pin | Arduino Pin |
|---|---|
| Button pin 1.l | Pin 2 |
| Button pin 2.l | GND |
| Resistor Pin 1 | Pin 13 |
| LED Anode (+) | Resistor Pin 2 |
| LED Cathode (−) | GND |