Execute code only once I am trying to create an if statement that only runs once, the very first time the void loop is started and switches to another code after that. But the following only executes stepper1a(). Any help would be great. Thx !



int var;
int var2;
bool executed = false;

const int M1dirpin = 4; //Stepper Dir Pin
const int M1steppin = 5; //Stepper Step Pin

void setup() {

pinMode(A2,INPUT);
pinMode(M1dirpin,OUTPUT);
pinMode(M1steppin,OUTPUT);
Serial.begin(9600);

}

void stepper1() { 
  int j;
    delayMicroseconds(10);
    digitalWrite(M1dirpin,HIGH);
  for(j=0;j&lt;=200;j++){
    digitalWrite(M1steppin,LOW);
    delayMicroseconds(10);
    digitalWrite(M1steppin,HIGH);
    delay(2);
  }
}

void stepper1a() {
  int j;
    delayMicroseconds(10);
    digitalWrite(M1dirpin,HIGH);
  for(j=0;j&lt;=1600;j++){
    digitalWrite(M1steppin,LOW);
    delayMicroseconds(10);
    digitalWrite(M1steppin,HIGH);
    delay(2);
  }
}

void loop() {

if (executed == false) {
var = analogRead(A2);
delay(10);
if (var &gt; 500) {
  stepper1a();
  delay(2000);
  executed = true;
  Serial.println("turned 1600");
  Serial.println(executed);
  }
else if (executed == true) {
 var2 = analogRead(A2);
delay(10);
if (var &gt; 500) {
  stepper1();
  delay(2000);
  Serial.println("turned 200");
}
}
}
}


Updated void loop:

void loop() {

    static bool yes_we_did_the_one_time_job = false;

    if (yes_we_did_the_one_time_job) {
        var = analogRead(A2);
        delay(10);
        if (var &gt; 500) {
            stepper2();
            delay(2000);
            Serial.println("turned 1600");
        } 
    }
    else {
        var2 = analogRead(A2);
        delay(10);
        if (var &gt; 500) {
            stepper1();
            delay(2000);
            Serial.println("turned 200");
            yes_we_did_the_one_time_job = true;
        }
    }
}


This works now, thx !!!: 

void loop() {
  static bool yeswedid = false;

  if(yeswedid) {
    if(analogRead(A2) &gt; 500) {
    stepper1();
    stepper2();
    }
  }
  else {
    if(analogRead(A2) &gt; 500) {
    stepper1();
    yeswedid = true;
  }

  }
}
Generic solution:

void loop() {
    static bool yes_we_did_the_one_time_job = false;
    if (yes_we_did_the_one_time_job) {
        do_the_other_jobs();
    } else {
        do_the_one_time_job();
        yes_we_did_the_one_time_job = true;
    }
}