Please read How to get the best out of this forum before posting
What do you mean 'not working'? Is it a syntax error? A functionality error? What is it supposed to do?
Try this:
const int BUTTONS[] = {2, 3, 4, 5, 13, 7, 22};
const int RELAYS[] = {8, 9, 10, 11, 12, 6, 23};
const int NUM_RELAYS = sizeof(RELAYS) / sizeof(RELAYS[0]);
unsigned long lastActionTime = 0;
const unsigned long timeout = 120000;
void setup() {
for (int i = 0; i < NUM_RELAYS; i++) {
pinMode(BUTTONS[i], INPUT_PULLUP);
pinMode(RELAYS[i], OUTPUT);
digitalWrite(RELAYS[i], LOW); // All relays start ON (active LOW)
}
}
void loop() {
bool buttonPressed = false;
for (int i = 0; i < NUM_RELAYS; i++) {
if (!digitalRead(BUTTONS[i])) { // Button active LOW
activateRelay(i);
buttonPressed = true;
break; // Only one relay active at a time
}
}
if (!buttonPressed && millis() - lastActionTime > timeout) {
activateRelay(-1); // Turn all relays ON after timeout
}
}
void activateRelay(int relayNumber) {
// Turn all relays OFF (inactive = HIGH)
for (int i = 0; i < NUM_RELAYS; i++) {
digitalWrite(RELAYS[i], HIGH);
}
// If valid relayNumber, turn it ON (active = LOW)
if (relayNumber >= 0 && relayNumber < NUM_RELAYS) {
digitalWrite(RELAYS[relayNumber], LOW);
}
lastActionTime = millis();
}
This fixes the issue of you not actually controlling relay 6, the stray 'programming' comment at the bottom, and uses loops and arrays instead of repetitive code