CNAP
03 / Templates · beginner

PUSHBUTTON TOGGLE LED

Open in Playground

Press 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
Circuit
Code
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;
}
Components
  • Arduino Uno
    01
  • Pushbutton (wokwi-pushbutton)
    02
  • LED (red)
    03
  • Resistor 220Ω
    04
Wiring
Component PinArduino Pin
Button pin 1.lPin 2
Button pin 2.lGND
Resistor Pin 1Pin 13
LED Anode (+)Resistor Pin 2
LED Cathode (−)GND