Arduino Push Button LED: Wiring and Code

Now the Arduino listens. When you press the button, pin 2 reads HIGH and the LED turns on.

Parts you need

Wiring

  1. Button: one leg → 5V rail, other leg → pin 2
  2. Pin 13 → resistor → LED → GND rail

Arduino code

int button = 2;
int led = 13;

void setup() {
  pinMode(button, INPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  if (digitalRead(button) == HIGH) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
}

Goal and tip

Goal: Hold the button to light the LED, then let go to switch it off.

Tip: Try this: swap HIGH and LOW inside the if statement, so the LED is on until you press.

Run this experiment in the free simulator