Control an LED with a button on Arduino
Hi, this is my first article, and I will present a very simple project where we will control an LED using a push-button.
Required components:
-
Arduino board (I used an UNO, but any Arduino-compatible board works)
-
Push-button
-
LED (or you can use the built-in LED on pin 13)
-
220Ω resistor (only if you use an external LED)
-
Jumper wires
-
Breadboard (optional, but recommended)

Connections:
Led:
- short leg to 12
- long leg to 12
Button:
- one pin to 2
- the other to 12
Code:
const int ledPin = 12;
const int buttonPin = 2;
bool ledState = false;
int lastButtonState = HIGH;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
digitalWrite(ledPin, LOW);
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading == LOW && lastButtonState == HIGH) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
delay(200); // mic debounce
}
lastButtonState = reading;
}
