// Pin Definitions
const int relay1Pin = 2;
const int relay2Pin = 3;
const int relay3Pin = 4;
const int switch1Pin = 5;
const int switch2Pin = 6;
const int button1Pin = 7;
const int button2Pin = 8;
const int button3Pin = 9;
const int button4Pin = 10;
const int modeSwitchPin = 11;
const int potentiometerPin = A0;

// Global Variables
boolean isAutoMode = false;
boolean relay1Active = false;
boolean relay2Active = false;
boolean relay3Active = false;

void setup() {
  // Initialize pin modes
  pinMode(relay1Pin, OUTPUT);
  pinMode(relay2Pin, OUTPUT);
  pinMode(relay3Pin, OUTPUT);
  pinMode(switch1Pin, INPUT_PULLUP);
  pinMode(switch2Pin, INPUT_PULLUP);
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);
  pinMode(button3Pin, INPUT_PULLUP);
  pinMode(button4Pin, INPUT_PULLUP);
  pinMode(modeSwitchPin, INPUT_PULLUP);

  // Serial communication for debugging
  Serial.begin(9600);
}

void loop() {
  // Read mode switch input
  isAutoMode = digitalRead(modeSwitchPin);

  if (isAutoMode) {
    // Automatic Mode
    if (digitalRead(button1Pin) == LOW) {
      activateRelay1();
      delay(100);  // Debounce delay
    }

    if (digitalRead(switch1Pin) == LOW) {
      deactivateRelay1();
      activateRelay2();
    }

    if (digitalRead(switch2Pin) == LOW) {
      deactivateRelay2();
      activateRelay3();
      delay(getPotentiometerValue()); // Delay based on potentiometer value
      deactivateRelay3();
    }
  } else {
    // Manual Mode
    if (digitalRead(button2Pin) == LOW) {
      toggleRelay(relay1Pin);
      delay(100);  // Debounce delay
    }

    if (digitalRead(button3Pin) == LOW) {
      toggleRelay(relay2Pin);
      delay(100);  // Debounce delay
    }

    if (digitalRead(button4Pin) == LOW) {
      toggleRelay(relay3Pin);
      delay(100);  // Debounce delay
    }
  }
}

void activateRelay1() {
  digitalWrite(relay1Pin, HIGH);
  relay1Active = true;
  Serial.println("Relay 1 activated");
}

void deactivateRelay1() {
  digitalWrite(relay1Pin, LOW);
  relay1Active = false;
  Serial.println("Relay 1 deactivated");
}

void activateRelay2() {
  digitalWrite(relay2Pin, HIGH);
  relay2Active = true;
  Serial.println("Relay 2 activated");
}

void deactivateRelay2() {
  digitalWrite(relay2Pin, LOW);
  relay2Active = false;
  Serial.println("Relay 2 deactivated");
}

void activateRelay3() {
  digitalWrite(relay3Pin, HIGH);
  relay3Active = true;
  Serial.println("Relay 3 activated");
}

void deactivateRelay3() {
  digitalWrite(relay3Pin, LOW);
  relay3Active = false;
  Serial.println("Relay 3 deactivated");
}

void toggleRelay(int pin) {
  if (digitalRead(pin) == LOW) {
    digitalWrite(pin, HIGH);
    Serial.println("Relay activated");
  } else {
    digitalWrite(pin, LOW);
    Serial.println("Relay deactivated");
  }
}

int getPotentiometerValue() {
  return map(analogRead(potentiometerPin), 0, 1023, 1000, 10000);
}

NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module