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
- The button pin is set with
INPUT_PULLUP, so:- Pressed โ LOW (0)
- Released โ HIGH (1)
- When pressed, the code enters the blink section:
- Uses
millis()to toggle LED every 500 ms (non-blocking).
- Uses
- When released, LED turns OFF immediately.
โ๏ธ Circuit Wiring (same as your setup)
| Component | Arduino Pin | Other Connection |
|---|---|---|
| LED (Anode +) | D5 | Through 220ฮฉ resistor |
| LED (Cathode โ) | GND | โ |
| Push Button | D2 | One end to D2 |
| Push Button | GND | Other 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)?
Pingback: Arduino Demo Kit Projects - Motion Demo Kit (With Arduino) - Project List - EDGENext Learning