// Variable Definitions
#define buttonPin 12 // The Push-Button pin.
#define relayPin 13 // The relay pin (Light-Emitting Diode).
// Constants
const unsigned long debounceTime = 20; // Th Debounce time for the Push-Button.
// Variables
bool relayState = HIGH; // The variable for the current state of the relay 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(buttonPin, INPUT); // Set the Push-Button pin mode as an input.
pinMode(relayPin, OUTPUT); // Set the relay pin mode as an output.
digitalWrite(relayPin, relayState); // Write the relay with an initial state.
}
void loop() {
bool currButtonState = digitalRead(buttonPin); // 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 relay state.
if (buttonState == HIGH) {
relayState = !relayState; // Toggle the relay state
}
}
}
digitalWrite(relayPin, relayState); // Write the relay with an initial state.
prevButtonState = currButtonState; // Set the previous push-button state with the current push-button state.
}