Using flag to do a particular action only once

Hi! I am currently facing some problems when trying to use a flag to do a particular action only once. I wanted to print the value to move forward and turn left and continue to move forward all the way but this coding that I have done, it returns me forward, turn left, forward, turn right, forward, turn right and so on... Can anyone help me with this? Thank You so much!

int set1_flag = 0;

int previousAngle = 270;
int angleDouble = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (angleDouble >= 0 && angleDouble < 90)  
  {   
    Serial.println("Forward");
    delay(2000);
    if ((angleDouble <= previousAngle - 270) && (set1_flag == 0))
    {
      Serial.println("Turn Left");
      set1_flag = 1;
      delay(1000);
    }
    else
    {
      Serial.println("Turn Right");
      delay(1000);
    }
  }
}

I don't actually understand what you want to happen.

The outcome that you describe

Forward                                                                  
Turn Left                                                                
Forward                                                                  
Turn Right                                                               
Forward
Turn Right
Forward
Turn Right
Forward
Turn Right

is what the program code is designed to produce

If you only want it to print "Forward" after the first left or right then you should test for the flag first - something like this

if (set1_flag == 0) {
  // do stuff
  set1_flag = 1;
}

...R

Robin2:
I don't actually understand what you want to happen.

Thanks for the reply! I will try out the codes too. The outcome that I want is as follows:
Forward
Turn Left
Forward
Forward
Forward
Forward

Thank You for the reply! :slight_smile:

I have found out the way to solve this problem and would like to share it here. The codes are as follows:

int set1_flag = 0;

int previousAngle = 270;
int angleDouble = 0;

void setup() {
 // put your setup code here, to run once:
 Serial.begin(9600);
}

void loop() {
 // put your main code here, to run repeatedly:
 if (angleDouble >= 0 && angleDouble < 90)  //testing range for 270 and 360 turn left only
 {   
   Serial.println("Forward");
   delay(2000);
   if(set1_flag == 0)
   {
     if ((angleDouble <= previousAngle - 270))
     {
       Serial.println("Left");
       Serial.print("Minus Angle: ");
       Serial.println(previousAngle - 270);
       Serial.println();
       set1_flag = 1;
       delay(1000);
     }
     else
     {
       Serial.println("Right Side");
       set1_flag = 1;
       delay(1000);
     }
   }
 }
}