// constants won't change
const int BUTTON_PIN = 7; // Arduino pin connected to button's pin
const int LED_PIN = 3; // Arduino pin connected to LED's pin
// variables will change:
int ledState = LOW; // the current state of LED
int lastButtonState; // the previous state of button
int currentButtonState; // the current state of button
bool buttonPressed = false; // to track button press
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode
currentButtonState = digitalRead(BUTTON_PIN);
lastButtonState = currentButtonState;
}
void loop() {
lastButtonState = currentButtonState; // save the last state
currentButtonState = digitalRead(BUTTON_PIN); // read new state
// Detect button press (transition from HIGH to LOW)
if (lastButtonState == HIGH && currentButtonState == LOW) {
// Simple debounce - wait a bit to confirm the press
delay(50);
currentButtonState = digitalRead(BUTTON_PIN);
if (currentButtonState == LOW) { // confirmed press
buttonPressed = true;
}
}
// Only toggle LED when button is released (LOW to HIGH)
if (buttonPressed && currentButtonState == HIGH && lastButtonState == LOW) {
ledState = !ledState; // toggle LED state
digitalWrite(LED_PIN, ledState);
Serial.print("Button released. LED is now ");
Serial.println(ledState == HIGH ? "ON" : "OFF");
buttonPressed = false; // reset flag
}
}