// Define LED pin and button pin
const int ledPin = 2; // Onboard LED or any GPIO
const int buttonPin = 3; // Button pin
// Variables for button state and delay time
int buttonState = 0;
int lastButtonState = 0; // Previous state of the button
int delayTime = 2000; // Initial delay of 1 second (1000 ms)
unsigned long lastDebounceTime = 0; // Last time button state was changed
unsigned long debounceDelay = 50; // Debounce delay (milliseconds)
void setup() {
// Initialize LED pin as output
pinMode(ledPin, OUTPUT);
// Initialize button pin as input with pull-up resistor
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
int reading = digitalRead(buttonPin); // Read the button state
// Check if the button state has changed (debouncing)
if (reading != lastButtonState) {
lastDebounceTime = millis(); // Reset debounce timer
}
// If enough time has passed since the last debounce
if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button is pressed (LOW due to pull-up)
if (reading == LOW) {
delayTime = (delayTime == 2000) ? 500 : 2000; // Toggle delay time between 1000ms and 500ms
}
}
lastButtonState = reading; // Update the button state for the next loop
// Blink LED with the current delay time
digitalWrite(ledPin, HIGH); // Turn on the LED
delay(delayTime); // Wait for the specified delay time
digitalWrite(ledPin, LOW); // Turn off the LED
delay(delayTime); // Wait for the specified delay time
}