// Pin Definitions
const int potPin = A0;   // Analog input for the potentiometer
const int relayPin = 6;  // Pin to control the relay
const int startPin = 2;  // Pin to start the loop

// Variables
int potValue;            // Current potentiometer value
int waitTime;            // Waiting time in seconds
bool loopActive = false; // Flag variable to control the loop

void setup() {
  pinMode(relayPin, OUTPUT);
  pinMode(startPin, INPUT_PULLUP);
  digitalWrite(relayPin, LOW);  // Set relay default state to off
}

void loop() {
  // Check if the start pin is HIGH to enter the loop
  if (digitalRead(startPin) == HIGH && !loopActive) {
    loopActive = true; // Activate the loop

    while (loopActive) {
      // Read the potentiometer value and calculate the waiting time
      potValue = analogRead(potPin);
      waitTime = map(potValue, 0, 1023, 5000, 40000); // Map the potentiometer value to the desired time range (5-40 seconds)

      // Turn on the relay for one second
      digitalWrite(relayPin, HIGH);
      delay(1000);
      digitalWrite(relayPin, LOW);

      // Wait for the desired time
      delay(waitTime);

      // Check if the start pin is still HIGH to continue the loop
      if (digitalRead(startPin) == LOW) {
        loopActive = false; // Deactivate the loop
      }
    }
  }
}
