const int S1_PIN = 2;
const int S2_PIN = 3;
const int R1_PIN = 4;
const int R2_PIN = 5;
const int R3_PIN = 6;
const int P1_PIN = 7;
const int T1_PIN = A0;

bool isPowerFailure = false;

void setup() {
  pinMode(S1_PIN, INPUT_PULLUP);
  pinMode(S2_PIN, INPUT_PULLUP);
  pinMode(R1_PIN, OUTPUT);
  pinMode(R2_PIN, OUTPUT);
  pinMode(R3_PIN, OUTPUT);
  pinMode(P1_PIN, INPUT_PULLUP);
  
  // Check initial position and move to S1 if needed during power-up
  if (digitalRead(S2_PIN) == HIGH || (digitalRead(S1_PIN) == HIGH && digitalRead(S2_PIN) == HIGH)) {
    digitalWrite(R1_PIN, HIGH);
    while (digitalRead(S1_PIN) == HIGH) {
      // Wait for S1 to be reached
    }
    digitalWrite(R1_PIN, LOW);
    isPowerFailure = true; // Set power failure flag
  }
}

void loop() {
  if (digitalRead(P1_PIN) == LOW) {
    digitalWrite(R2_PIN, HIGH);
    while (digitalRead(S2_PIN) == HIGH) {
      // Wait for S2 to close
    }
    digitalWrite(R2_PIN, LOW);
    
    digitalWrite(R1_PIN, HIGH);
    while (digitalRead(S1_PIN) == HIGH) {
      // Wait for S1 to be reached
    }
    digitalWrite(R1_PIN, LOW);
    
    int interval = map(analogRead(T1_PIN), 0, 1023, 1000, 10000);
    
    // Check if this is the power failure scenario
    if (isPowerFailure) {
      // If piston is in S2, activate R3 for its desired time
      if (digitalRead(S2_PIN) == LOW) {
        digitalWrite(R3_PIN, HIGH);
        delay(interval);
        digitalWrite(R3_PIN, LOW);
      }
      isPowerFailure = false; // Reset power failure flag
    } else {
      // Normal cycle: Turn on R3 after reaching S1
      digitalWrite(R3_PIN, HIGH);
      delay(interval);
      digitalWrite(R3_PIN, LOW);
    }
  }
}
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module