Practical Answers Hub · Learn Arduino UNO · Lessons 9–10

Button-Controlled LED and Latching Switch

Use the tested tactile switch to light an LED while held, then make each press toggle a stored on/off state.

Lesson 9 · LED on only while pressed

Keep the tested switch between D2 and GND with INPUT_PULLUP. Add an LED on D8, its own 220–330 Ω resistor, and GND.

Input and output
1D2 → tactile switch → GND (internal pull-up enabled)
2D8 → 220–330 Ω resistor → LED anode; cathode → GND
PHOTO TO ADDComplete breadboard showing switch across centre gap and the LED resistor.
const int buttonPin = 2;
const int ledPin = 8;
void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
}
void loop() {
  if (digitalRead(buttonPin) == LOW) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

Check: released = HIGH at the input and LED off; pressed = LOW and LED on.

Lesson 10 · Press once for on, again for off

A latch needs memory. A bool records whether the LED should remain on. Toggle it only at the start of a new press, then write that stored state to the LED.

const int buttonPin = 2;
const int ledPin = 8;
bool ledOn = false;
int previous = HIGH;
void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
}
void loop() {
  int current = digitalRead(buttonPin);
  if (current == LOW && previous == HIGH) {
    delay(30);
    if (digitalRead(buttonPin) == LOW) {
      ledOn = !ledOn;
      digitalWrite(ledPin, ledOn ? HIGH : LOW);
    }
  }
  previous = current;
}

Test one short press, one long hold, and a second press. The light should change once per press and stay in its new state after release.

VIDEO TO ADDDemonstrate momentary behaviour, then latching behaviour on the same circuit.