// https://wokwi.com/projects/424104606055576577
const byte relay1 = 12;
const byte relay2 = 11;
const byte button = 7;
# define ON HIGH
# define OFF LOW
# define PRESST LOW // switch wired to ground
const unsigned long pressTime = 400; // how long must we press the button for relay2
void setup()
{
Serial.begin (115200);
pinMode(button, INPUT_PULLUP);
digitalWrite(relay1, OFF);
digitalWrite(relay2, OFF);
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
}
unsigned long now;
bool lastButtonState;
bool relay1_ON;
bool relay2_ON;
bool waiting; // waiting for button to be pressed long enough
void loop()
{
static unsigned long lastTime;
now = millis();
bool buttonState = digitalRead(button) == PRESST;
if (lastButtonState != buttonState) {
lastTime = now;
waiting = true;
if (buttonState) {
relay1_ON = !relay1_ON;
}
lastButtonState = buttonState;
}
// lose the realy1_ON term to get relay2 on both edges
if (relay1_ON && waiting && now - lastTime > pressTime) {
relay2_ON = true;
waiting = false;
}
if (!buttonState) relay2_ON = false;
digitalWrite(relay1, relay1_ON ? ON : OFF);
digitalWrite(relay2, relay2_ON ? ON : OFF);
delay(20); // poor man's debounce
}
POWER
START