int swButton = 12;
int relayPin = 16;
bool relayOn = false; // Present on/off state of the relay.
int debounceTime = 200; // Debounce time in ms.
volatile bool switchToggle = false; // True when button press is valid (and not bounce noise).
volatile unsigned long nowPush = 0; // The millis() time of the present button press.
volatile unsigned long lastPush = 0; // The millis() time of the previous button press.
volatile unsigned long timeGap = 0; // The difference of the nowPush and lastPush times.
// Interrupt Service Routine on button press (falling edge).
ICACHE_RAM_ATTR void swButtonISR() {
nowPush = millis();
timeGap = nowPush - lastPush;
// Debouncing stuff, recognizing this button-press as a valid one.
if (timeGap > debounceTime) {
switchToggle = true;
lastPush = nowPush;
}
}
// Function that toggles the relay when called upon.
void toggleRelay () {
if (relayOn) {
digitalWrite(relayPin, LOW); // Turn off relay.
relayOn = false;
Serial.println("Relay ON");
return;
}
else {
digitalWrite(relayPin, HIGH); // Turn on relay.
relayOn = true;
Serial.println("Relay OFF");
return;
}
return;
}
void setup() {
Serial.begin(115200);
pinMode(swButton, INPUT);
pinMode(relayPin, OUTPUT);
//pinMode(greenLED, OUTPUT);
attachInterrupt(digitalPinToInterrupt(swButton), swButtonISR, FALLING);
}
void loop() {
if (switchToggle == true) {
toggleRelay();
switchToggle = false;
}
}