Push Button LED Control โ€“ Arduino Nano

๐ŸŸข The LED on D5 will blink only while the button on D2 is pressed,
and stay OFF when the button is released.

Weโ€™ll keep the same non-blocking (millis-based) blink logic โ€” no delay(), so it runs smoothly.

Circuit


โœ… LED Blinks Only While Button is Pressed

#define LED_PIN     5   // LED connected to D5
#define BUTTON_PIN  2   // Button connected to D2 (one side to GND, using INPUT_PULLUP)

#define BLINK_INTERVAL 500  // LED blink interval (milliseconds)

int led_state = LOW;           // Store current LED state
unsigned long prev_millis = 0; // Store last blink time

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP); // Internal pull-up resistor
  Serial.begin(9600);
}

void loop() {
  // Read button (LOW = pressed, HIGH = released)
  int button_state = digitalRead(BUTTON_PIN);

  if (button_state == LOW) {
    // If button is pressed, blink LED
    unsigned long current_millis = millis();

    if (current_millis - prev_millis >= BLINK_INTERVAL) {
      led_state = (led_state == LOW) ? HIGH : LOW;
      digitalWrite(LED_PIN, led_state);
      prev_millis = current_millis;
    }
  } else {
    // If button is not pressed, turn LED OFF
    digitalWrite(LED_PIN, LOW);
    led_state = LOW;
  }
}

๐Ÿง  How It Works

  1. The button pin is set with INPUT_PULLUP, so:
    • Pressed โ†’ LOW (0)
    • Released โ†’ HIGH (1)
  2. When pressed, the code enters the blink section:
    • Uses millis() to toggle LED every 500 ms (non-blocking).
  3. When released, LED turns OFF immediately.

โš™๏ธ Circuit Wiring (same as your setup)

ComponentArduino PinOther Connection
LED (Anode +)D5Through 220ฮฉ resistor
LED (Cathode โˆ’)GNDโ€”
Push ButtonD2One end to D2
Push ButtonGNDOther end to GND

โœ… Note: Because weโ€™re using INPUT_PULLUP, button must connect to GND (not 5V).

If your button is already wired to 5V, just change:

pinMode(BUTTON_PIN, INPUT);

and reverse the logic to:

if (button_state == HIGH) { // instead of LOW

Would you like me to generate a clear circuit diagram (image) for this exact wiring โ€”
LED on D5, button on D2 โ†’ GND (for INPUT_PULLUP type)?

This Post Has One Comment

Leave a Reply