const int BUTTON_PIN = 2; // Pin connected to the pushbutton
const int LED_PIN = 13; // Pin connected to the LED
int ledState = LOW; // Tracks the current output state
int buttonState = HIGH; // Tracks current reading from the input pin
int lastButtonState = HIGH; // Tracks the previous reading from the input pin
void setup() {
pinMode(LED_PIN, OUTPUT);
// INPUT_PULLUP enables the internal resistor, pulling the pin HIGH by default
pinMode(BUTTON_PIN, INPUT);
// Ensure the LED starts in our initial state
digitalWrite(LED_PIN, ledState);
}
void loop() {
// Read the current physical state of the button
buttonState = digitalRead(BUTTON_PIN);
// Check if the button state has changed (State Change Detection)
if (buttonState != lastButtonState) {
// Check if the state changed from HIGH to LOW (Button was just pressed)
if (buttonState == LOW) {
// Flip the toggle variable
ledState = !ledState;
// Apply the flipped state to the LED
digitalWrite(LED_PIN, ledState);
}
// Soft debounce delay to let mechanical noise settle
delay(50);
}
// Save the current state as the last state for the next loop iteration
lastButtonState = buttonState;
}