/*
https://forum.arduino.cc/t/4-buttons-to-control-4-relays/1109997
https://wokwi.com/projects/360921014043806721
=======================================
Switch one out of four relay on/off for 3 seconds
Block all buttons for a 2 minutes (here for test purposes 10 seconds only)
=======================================
2023-04-02
coded by ec2021
*/
constexpr byte button1Pin = 7;
constexpr byte button2Pin = 6;
constexpr byte button3Pin = 5;
constexpr byte button4Pin = 4;
constexpr byte relay1Pin = 13;
constexpr byte relay2Pin = 12;
constexpr byte relay3Pin = 11;
constexpr byte relay4Pin = 10;
struct ButtonType {
byte Pin;
unsigned long lastChange = 0;
int lastState = HIGH;
int state = HIGH;
boolean released();
};
boolean ButtonType::released() {
int actState = digitalRead(ButtonType::Pin);
if (actState != ButtonType::lastState) {
ButtonType::lastChange = millis();
ButtonType::lastState = actState;
}
if (actState != ButtonType::state && millis() - ButtonType::lastChange > 50) {
ButtonType::state = actState;
if (actState) return true;
};
return false;
}
ButtonType button1;
ButtonType button2;
ButtonType button3;
ButtonType button4;
constexpr int NoOfRelais = 4;
byte relayPin[NoOfRelais] = {relay1Pin, relay2Pin, relay3Pin,relay4Pin};
void setup() {
Serial.begin(115200);
Serial.println("Start");
button1.Pin = button1Pin;
button2.Pin = button2Pin;
button3.Pin = button3Pin;
button4.Pin = button4Pin;
pinMode(button1.Pin, INPUT_PULLUP);
pinMode(button2.Pin, INPUT_PULLUP);
pinMode(button3.Pin, INPUT_PULLUP);
pinMode(button4.Pin, INPUT_PULLUP);
for (int i = 0; i < NoOfRelais;i++) pinMode(relayPin[i], OUTPUT);
}
constexpr unsigned long RelaySwitchTime = 3000UL; // 3 sec = 3000 milliseconds
constexpr unsigned long ButtonBlockTime = 10000UL; // 10 sec = 10000 milliseconds
//constexpr unsigned long ButtonBlockTime = 120000UL; // 2 min = 120 sec = 120000 milliseconds
int SwitchNo = 0;
void loop() {
HandleButtons();
HandleRelaisOnOff();
}
void HandleButtons(){
static boolean BlockButtons = false;
static unsigned long lastButtonBlockTime = 0;
if (!BlockButtons) {
if (button1.released()) SwitchNo = 1;
if (button2.released()) SwitchNo = 2;
if (button3.released()) SwitchNo = 3;
if (button4.released()) SwitchNo = 4;
if (SwitchNo > 0) {
lastButtonBlockTime = millis();
BlockButtons = true;
Serial.println("Buttons disabled");
}
} else {
if (millis() - lastButtonBlockTime > ButtonBlockTime){
BlockButtons = false;
Serial.println("Buttons enabled");
}
}
}
void HandleRelaisOnOff(){
static int RelayOn = 0;
static boolean RelaySwitchedOn = false;
static unsigned long lastRelayOnTime = 0;
if (SwitchNo) {
lastRelayOnTime = millis();
RelayOn = SwitchNo-1;
SwitchNo = 0;
digitalWrite(relayPin[RelayOn],HIGH);
RelaySwitchedOn = true;
Serial.println("Relay\t"+String(RelayOn+1)+ " on");
}
if (RelaySwitchedOn && millis() - lastRelayOnTime > RelaySwitchTime){
digitalWrite(relayPin[RelayOn],LOW);
RelaySwitchedOn = false;
Serial.println("Relay\t"+String(RelayOn+1)+ " off");
}
}