// Define pin numbers
const int buttonPin = 2; // Pin for the push button
const int ledPin = 8; // Pin for the LED
// Variables to store the button state and LED state
int buttonState = 0;
int lastButtonState = 0;
int ledState = LOW;
void setup() {
// Set the button pin as input
pinMode(buttonPin, INPUT);
// Set the LED pin as output
pinMode(ledPin, OUTPUT);
// Initialize LED as OFF
digitalWrite(ledPin, ledState);
}
void loop() {
// Read the current state of the button
buttonState = digitalRead(buttonPin);
// Check if the button state has changed
if (buttonState != lastButtonState) {
// If the button is pressed, toggle the LED
if (buttonState == HIGH) {
ledState = !ledState;
digitalWrite(ledPin, ledState); // Set the LED to the new state
}
// Small delay for debouncing
delay(50);
}
// Save the current button state for comparison in the next loop
lastButtonState = buttonState;
}