#define BUTTON_PIN A0 // Pin for reading the button state
#define LED_PIN 7 // Pin for the LED output
#define DEBOUNCE_PERIOD 10 // Debounce delay: 10 milliseconds
enum {
PRESSED = LOW, // State representing a pressed button
RELEASED = HIGH // State representing a released button
};
bool currentButtonState = RELEASED; // Current state of the button
bool previousButtonState = RELEASED; // Previous state of the button
bool ledState = false; // Current state of the LED
void setup() {
Serial.begin(115200); // Initialize serial communication at 115200 baud rate
pinMode(BUTTON_PIN, INPUT_PULLUP); // Set button pin as input with internal pull-up resistor
pinMode(LED_PIN, OUTPUT); // Set LED pin as output
}
void loop() {
// Main program loop
// Check for debounced button press and toggle the LED accordingly
if (instantDebouncer()) {
ledState = !ledState; // Toggle the LED state
digitalWrite(LED_PIN, ledState); // Update the LED state
}
}
// Function to debounce the button input
boolean instantDebouncer() {
static bool isDebouncing = false; // Flag to indicate ongoing debounce process
static unsigned long debounceStartTime = 0; // Timestamp for tracking debounce duration
bool returnValue = false; // Variable to hold the debounced button state
unsigned long currentTime = millis(); // Current time in milliseconds
bool buttonState = digitalRead(BUTTON_PIN); // Read the current state of the button
// Check for state change and reset debounce timer if necessary
if (buttonState != previousButtonState) {
debounceStartTime = currentTime; // Reset debounce timer
}
// Debounce the button input
if (isDebouncing) {
if (currentTime - debounceStartTime >= DEBOUNCE_PERIOD) {
isDebouncing = false; // Reset debounce flag
}
} else {
if (buttonState != currentButtonState) {
isDebouncing = true; // Start debounce process
currentButtonState = buttonState; // Update current button state
returnValue = (currentButtonState == PRESSED); // Set return value if button is pressed
}
}
previousButtonState = buttonState; // Update previous button state for the next iteration
return returnValue; // Return the debounced button state
}