CYTHEIA AIOpen the editor

Button Controlled LED

Press a button to turn on an LED.

Open this circuit and run it

Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.

How it works

A push button connects 5 volts to pin 2. While the button is pressed, pin 2 sees 5 volts and reads high; when it is not pressed, it reads low. The LED on pin 13 (through a resistor, to ground) is the output. On real hardware you would also add a resistor from pin 2 to ground, called a pull-down and usually 10 kΩ, so the pin reads a clean low when the button is open instead of floating.

loop() reads pin 2 with digitalRead() about ten times a second. If it reads HIGH the sketch lights the LED and prints “Button pressed - LED ON”; otherwise it switches the LED off and prints “Button released - LED OFF”. Click and hold the button in the editor while it runs to see the LED follow it.

Parts

Wiring

Arduino code

// Button Controlled LED
void setup() {
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(2);
  if (buttonState == HIGH) {
    digitalWrite(13, HIGH);
    Serial.println("Button pressed - LED ON");
  } else {
    digitalWrite(13, LOW);
    Serial.println("Button released - LED OFF");
  }
  delay(100);
}

Try changing it

Open this circuit and run it

Next challenge

More projects in Input & Controls