# define PRESSED LOW // Change to HIGH if button drives HIGH when pressed
# define ON HIGH // Change to LOW if relay module is active-LOW
# define OFF LOW // Change to HIGH if
const byte inputPin = 2; // Input signal pin
const byte relayPin[2] = {8, 9};
const unsigned long WINDOW = 4000UL; // 4 seconds: life is short! 10-second recovery window
const unsigned long PULSE = 777; // relay pulse duration
bool lastInput;
void setup() {
Serial.begin(115200);
pinMode(inputPin, INPUT_PULLUP);
for (byte ii = 0; ii < 2; ii++) {
pinMode(relayPin[ii], OUTPUT);
digitalWrite(relayPin[ii], OFF);
}
lastInput = digitalRead(inputPin) == PRESSED;
}
byte nextRelay = 0; // 0 means relay1 next, 1 for relay2
unsigned long windowTimer = 0;
unsigned long pulseTimer;
void loop()
{
unsigned long now = millis();
// free running loop at this point
// rest of loop operates at 50 Hz
static unsigned long lastTime;
bool inputNow = digitalRead(inputPin) == PRESSED;
if (now - lastTime < 20)
return;
lastTime = now;
bool risingEdge = (inputNow && !lastInput);
bool fallingEdge = (!inputNow && lastInput);
lastInput = inputNow;
if (risingEdge) {
digitalWrite(relayPin[nextRelay], ON);
pulseTimer = now;
}
if (inputNow)
windowTimer = now;
if (now - windowTimer >= WINDOW)
nextRelay = 0; // reset to use relay1 first
if (now - pulseTimer > PULSE) {
digitalWrite(relayPin[0], OFF);
digitalWrite(relayPin[1], OFF);
}
if (fallingEdge)
nextRelay = 1 - nextRelay; // switch to the other relay
// delay(20); // poor man's debounce no longer needed
}
;;//
//;;