⭐ Beginner
⏱️ 15 minutes
Light switch
You are making a light switch. Press once: the LED turns on. Press again: the LED turns off. This is how you learn how the Arduino "feels" a button.
🧰 What do you need?
🗺️ Wiring diagram
Follow the wires from the Arduino to each part. You can choose the wire colors yourself.
| From | To |
|---|---|
Arduino UNO · D2 |
Push button · 1 |
Push button · 2 |
Arduino UNO · GND |
Arduino UNO · D13 |
Resistor 220 Ω · 1 |
Resistor 220 Ω · 2 |
LED (little light) · ANODE |
LED (little light) · CATHODE |
Arduino UNO · GND |
🛠️ This is how you build it
- Put the push button over the gap in your breadboard.
- Connect one leg to pin 2 and a leg on the other side to GND.
- Put the LED with a 220 Ω resistor on pin 13, with the short leg to GND.
💻 The code
// Light switch
// Press the button once: the LED turns on. Again: the LED turns off.
const int BUTTON_PIN = 2; // The push button is on pin 2 (other side to GND)
const int LED_PIN = 13; // The LED is on pin 13 (through the resistor)
bool ledOn = false; // Remembers if the LED is on or off now
bool previousButton = HIGH; // How the button was last time
void setup() {
pinMode(BUTTON_PIN, INPUT_PULLUP); // Input with built-in resistor: loose = HIGH, pressed = LOW
pinMode(LED_PIN, OUTPUT);
}
void loop() {
bool button = digitalRead(BUTTON_PIN);
// Only react at the moment you press the button
if (previousButton == HIGH && button == LOW) {
ledOn = !ledOn; // Flip: on becomes off, off becomes on
digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
delay(50); // Wait a little to stop button "bounce"
}
previousButton = button;
}
🧠 What does the code do?
- The button is on pin 2 with
INPUT_PULLUP. Not pressed is HIGH, pressed is LOW. - We remember if the LED is on or off in
ledOn. - Only at the moment you press the button, we flip
ledOn.
🎯 Try this…
- Make the LED blink instead of staying on
- Let the LED turn off by itself after 10 seconds
- Count how many times the button is pressed and show it in the serial monitor
🚀 Build this project with Codey: open codey.online/starter-kits/uno/projects/light-switch and click MAKE THIS. Then the code and the wiring diagram are ready right away.
Codey Online is a product of OTRONIC