// Variable Definitions
#define pbPin 12 // The Push-Button pin.
#define ledPin 13 // The LED pin (Light-Emitting Diode).
// Constants
const unsigned long debounceTime = 20; // Th Debounce time for the Push-Button.
// Variables
bool ledState = HIGH; // The variable for the current state of the LED with an initial state.
bool buttonState; // The variable for current reading value from the Push-Button pin.
bool prevButtonState = LOW; // The variable for previous reading value from the Push-Button pin.
unsigned long prevDebounceTime = 0; // The variable for the previous time Push-Button change.
void setup() {
pinMode(pbPin, INPUT); // Set the Push-Button pin mode as an input.
pinMode(ledPin, OUTPUT); // Set the LED pin mode as an output.
digitalWrite(ledPin, ledState); // Write the LED with an initial state.
}
void loop() {
bool currButtonState = digitalRead(pbPin); // Read the current Push-Button state.
// Read a Push-Button value and compare the current value with the previous value.
// If the Push-Button value is different, reset the debounce time.
if (currButtonState != prevButtonState) {
prevDebounceTime = millis(); // Reset the debounce time
}
// If the Push-Button state is different from the current value, continue to debounce the Push-Button
if (buttonState != currButtonState) {
// If the current value is stable, fully debounce time.
// Set the push-button state with the current value
if ((millis() - prevDebounceTime) >= debounceTime) {
buttonState = currButtonState; //Set the push-button state with the current value
// In PULL-DOWN mode, the push-button pressed state is HIGH.
// If the push-button state is HIGH, toggle the LED state.
if (buttonState == HIGH) {
ledState = !ledState; // Toggle the LED state
}
}
}
digitalWrite(ledPin, ledState); // Write the LED with an initial state.
prevButtonState = currButtonState; // Set the previous push-button state with the current push-button state.
}