// Pin assignment
const int ledPin = 13; // LED connected to digital pin 13
const int buttonPin = 2; // Push button connected to digital pin 2
bool ledState = LOW; // Current state of the LED (OFF by default)
bool buttonState = HIGH; // Current state of the button
bool lastButtonState = HIGH; // Previous button state
void setup() {
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(buttonPin, INPUT_PULLUP); // Set button pin as input with internal pull-up
}
void loop() {
// Read the current state of the button
buttonState = digitalRead(buttonPin);
// Check if the button is pressed (active low) and detect state change
if (buttonState == LOW && lastButtonState == HIGH) {
// Toggle the LED state
ledState = !ledState;
digitalWrite(ledPin, ledState);
}
// Store the current button state for the next loop
lastButtonState = buttonState;
delay(50); // Debounce delay to avoid rapid toggling
}