Executing a part of the program only once

I’m designing an automatic changeover of a generator using Arduino. When the EB power is off, I need to switch on the generator starting motor for five seconds, then switch it off and then switch on the contactor C2. When the generator is ON and now if EB power comes in, I have to switch OFF the contactor C2, switch ON the generator stop motor for five seconds and then switch ON the contactor C2. My code is

int ebin = 2; // EB input
int gin = 3; // Generator input
int GonR1 = 4; // Generator ON (Relay 1) starting motor
int GoffR2 = 5; // Generator OFF (Relay 2) stopping motor
int C1 = 6; // Contactor 1
int C2 = 7; //Contactor 2
int e = 0;
int g = 0;

void setup() {

pinMode(ebin,INPUT);
pinMode(gin,INPUT);
pinMode(GonR1,OUTPUT);
pinMode(GoffR2,OUTPUT);
pinMode(C1,OUTPUT);
pinMode(C2,OUTPUT);
}

void loop() {

e = digitalRead(ebin);
g = digitalRead(gin);

if(e==LOW)
{
digitalWrite(GoffR2, LOW);
digitalWrite(C1, LOW);
delay(4000);
digitalWrite(GonR1, HIGH);
delay(5000);
digitalWrite(GonR1, LOW);

digitalWrite(C2, HIGH);

}

else if(e==HIGH && g==LOW)
{

digitalWrite(GoffR2, LOW);
digitalWrite(GonR1, LOW);
digitalWrite(C2, LOW);
digitalWrite(C1, HIGH);

}

else if(g==HIGH && e==HIGH)
{

digitalWrite(GonR1, LOW);
delay(5000);
digitalWrite(C2, LOW);
digitalWrite(GoffR2, HIGH);
delay(4000);
digitalWrite(GoffR2, LOW);
digitalWrite(C1, HIGH);
}
}

When e==LOW, I want this part

digitalWrite(GoffR2, LOW);
digitalWrite(C1, LOW);
delay(4000);
digitalWrite(GonR1, HIGH);
delay(5000);
digitalWrite(GonR1, LOW);

to execute only once and I want this part

digitalWrite(C2, HIGH);

to be executed continuously until the condition fails.

But the reality is when the condition (e==LOW) is true the entire loop gets executed continuously. This will make the generator starter motor to run every 4 seconds. So I need help to solve this problem. Thanks in advance.

Record when you've done that step in a global variable, and check that as well as the state of the pin.

Consider using a statemachine. Inthe first state, if a condition is true (e==low), do something and go to the next state. Wait in that next state for another condition to become true (e.g some form of delay) and go to the next state etc. At the end, go back to the first state.

Use of a switch/case will probably make this simple.