const int BTN_PIN = 8;
const int RELAY_PIN = 7;
bool isRelayOn = false;
int oldBtnState = HIGH;
bool checkButton() {
bool wasPressed = false;
int btnState = digitalRead(BTN_PIN); // read the pin
if (btnState != oldBtnState) { // if it changed
oldBtnState = btnState; // remember the state
if (btnState == LOW) { // was just pressed
//Serial.println("Button Pressed");
wasPressed = true;
} else { // was just released
//Serial.println("Button Released");
}
delay(20); // short delay to debounce button
}
return wasPressed;
}
void setup() {
Serial.begin(115200);
pinMode(BTN_PIN, INPUT_PULLUP);
pinMode(RELAY_PIN, OUTPUT);
}
void loop() {
int btnPressed = checkButton();
if (btnPressed) isRelayOn = !isRelayOn;
digitalWrite(RELAY_PIN, isRelayOn);
}