Help with a human following robot

Hello all,
I have been working on a robot that will follow someone at a set distance using a ultrasonic distance sensor. The code was working but i needed to add millis instead of delays and now the robot has stopped working. any help or suggestions would be appreciated!

here is my code:

#define echoPin 10 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 7 //attach pin D3 Arduino to pin Trig of HC-SR04

long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

unsigned long previousmillis = 0;
const long period = 500;

void setup() {
  
  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin

  //Setup Channel B
  pinMode(13, OUTPUT); //Initiates Motor Channel A pin
  pinMode(8, OUTPUT);  //Initiates Brake Channel A pin

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");

}

//start direction functions

void forward()
{
  //Motor A forward @ full speed
  digitalWrite(12, HIGH);  //Establishes backward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);    //Spins the motor on Channel A at half speed
  
  //Motor B forward @ full speed
  digitalWrite(13, LOW); //Establishes forward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);   //Spins the motor on Channel B at full speed
}

void brake()
{
    //Motor A stop
  digitalWrite(12, LOW);  //Establishes backward direction of Channel A
  digitalWrite(9, HIGH);   //Disengage the Brake for Channel A
  analogWrite(3, 0);    //Spins the motor on Channel A at half speed
  
  //Motor B stop
  digitalWrite(13, LOW); //Establishes forward direction of Channel B
  digitalWrite(8, HIGH);   //Disengage the Brake for Channel B
  analogWrite(11, 0);   //Spins the motor on Channel B at full speed
}

void turnr()
{
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  //Motor B backward @ half speed
  digitalWrite(13, HIGH);  //Establishes backward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at half speed
}
void turnl()
{
  digitalWrite(12, LOW); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  //Motor B backward @ half speed
  digitalWrite(13, LOW);  //Establishes backward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at half speed


}

//start loop

void loop(){
  // Clears the trigPin condition
  digitalWrite(trigPin, LOW);
  delayMicroseconds(1);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(2);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
unsigned long currentMillis = millis();

  
    if (distance >= 130){
       brake();
      if (currentMillis - previousmillis >= period) 
        turnr();
        previousmillis = currentMillis;
      if (currentMillis - previousmillis >= period)  
          brake();
           previousmillis = currentMillis;
       if (currentMillis - previousmillis >= period) 
           turnl(); 
           previousmillis = currentMillis;
     if (currentMillis - previousmillis >= period)  
          brake();
          previousmillis = currentMillis;
      { }

    }else{
     forward();

    }

  if (distance <= 40){
        brake();
      if (currentMillis - previousmillis >= period) 
        turnr();
        previousmillis = currentMillis;
      if (currentMillis - previousmillis >= period)  
          brake();
           previousmillis = currentMillis;
       if (currentMillis - previousmillis >= period) 
           turnl(); 
           previousmillis = currentMillis;
     if (currentMillis - previousmillis >= period)  
          brake();
          previousmillis = currentMillis;
      { }

    }else{
     forward();

  
    }}
  
//end loop


   
  if (distance >= 130)
  {
    brake();
    if (currentMillis - previousmillis >= period)
      turnr();
    previousmillis = currentMillis;
    if (currentMillis - previousmillis >= period)
      brake();
    previousmillis = currentMillis;
    if (currentMillis - previousmillis >= period)
      turnl();
    previousmillis = currentMillis;
    if (currentMillis - previousmillis >= period)
      brake();
    previousmillis = currentMillis;

It looks like you screwed up this set of if statements and their dependant code. As it stands, each of the lines setting the value of previousmillis will be executed unconditionally if distance is greater than or equal to 130. Note how the use of Auto Format in the IDE has highlighted this

how do I fix this?

Unlike Python, C++ doesn't group statements by indentation level. You have to put brackets around groups of statements to make them act like a single statement:

void loop()
{
  // Clears the trigPin condition
  digitalWrite(trigPin, LOW);
  delayMicroseconds(1);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(2);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  unsigned long currentMillis = millis();


  if (distance >= 130)
  {
    brake();
    
    if (currentMillis - previousmillis >= period)
    {
      turnr();
      previousmillis = currentMillis;
    }
    
    if (currentMillis - previousmillis >= period)
    {
      brake();
      previousmillis = currentMillis;
    }
    
    if (currentMillis - previousmillis >= period)
    {
      turnl();
      previousmillis = currentMillis;
    }
    
    if (currentMillis - previousmillis >= period)
    {
      brake();
      previousmillis = currentMillis;
    }

  }
  else
  {
    forward();
  }

  if (distance <= 40)
  {
    brake();
    
    if (currentMillis - previousmillis >= period)
    {
      turnr();
      previousmillis = currentMillis;
    }
    
    if (currentMillis - previousmillis >= period)
    {
      brake();
      previousmillis = currentMillis;
    }
    
    if (currentMillis - previousmillis >= period)
    {
      turnl();
      previousmillis = currentMillis;
    }
    
    if (currentMillis - previousmillis >= period)
    {
      brake();
      previousmillis = currentMillis;
    }
  }
  else
  {
    forward();
  }
} //end loop

Thank you!

The code still seems odd. For instance, what exactly will happen when currentMillis - previousmillis is greater than or equal to period ?

either the bot will turn or brake depending on the following code

if (currentMillis - previousmillis >= period)
    {
      turnr();
      previousmillis = currentMillis;
    }

    if (currentMillis - previousmillis >= period)
    {
      brake();
      previousmillis = currentMillis;
    }

I think not.

If the period has ended then the first if test will return true and the turnr() function will be called. What would cause the brake() function to be called ?

would this fix it?

#define echoPin 10 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 7 //attach pin D3 Arduino to pin Trig of HC-SR04

long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

unsigned long previousmillis = 0;
const long period1 = 500;
const long period2 = 505;
const long period3 = 510;
const long period4 = 515;
void setup() {

  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin

  //Setup Channel B
  pinMode(13, OUTPUT); //Initiates Motor Channel A pin
  pinMode(8, OUTPUT);  //Initiates Brake Channel A pin

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");

}

//start direction functions

void forward()
{
  //Motor A forward @ full speed
  digitalWrite(12, HIGH);  //Establishes backward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);    //Spins the motor on Channel A at half speed

  //Motor B forward @ full speed
  digitalWrite(13, LOW); //Establishes forward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);   //Spins the motor on Channel B at full speed
}

void brake()
{
  //Motor A stop
  digitalWrite(12, LOW);  //Establishes backward direction of Channel A
  digitalWrite(9, HIGH);   //Disengage the Brake for Channel A
  analogWrite(3, 0);    //Spins the motor on Channel A at half speed

  //Motor B stop
  digitalWrite(13, LOW); //Establishes forward direction of Channel B
  digitalWrite(8, HIGH);   //Disengage the Brake for Channel B
  analogWrite(11, 0);   //Spins the motor on Channel B at full speed
}

void turnr()
{
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  //Motor B backward @ half speed
  digitalWrite(13, HIGH);  //Establishes backward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at half speed
}
void turnl()
{
  digitalWrite(12, LOW); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  //Motor B backward @ half speed
  digitalWrite(13, LOW);  //Establishes backward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at half speed


}

//start loop

void loop() {
  // Clears the trigPin condition
  digitalWrite(trigPin, LOW);
  delayMicroseconds(1);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(2);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  unsigned long currentMillis = millis();


  if (distance >= 130)
  {
    brake();

   if (currentMillis - previousmillis >= period1)
    {
      turnr();
      previousmillis = currentMillis;
    }

    if (currentMillis - previousmillis >= period2)
    {
      brake();
      previousmillis = currentMillis;
    }

    if (currentMillis - previousmillis >= period3)
    {
      turnl();
      previousmillis = currentMillis;
    }

    if (currentMillis - previousmillis >= period4)
    {
      brake();
      previousmillis = currentMillis;
    }

  }
  else
  {
    forward();
  }

  if (distance <= 40)
  {
    brake();

    if (currentMillis - previousmillis >= period1)
    {
      turnr();
      previousmillis = currentMillis;
    }

    if (currentMillis - previousmillis >= period2)
    {
      brake();
      previousmillis = currentMillis;
    }

    if (currentMillis - previousmillis >= period3)
    {
      turnl();
      previousmillis = currentMillis;
    }

    if (currentMillis - previousmillis >= period4)
    {
      brake();
      previousmillis = currentMillis;
    }
  }
  else
  {
    forward();
  }
} //end loop

No

For instance, you are setting previousmillis to currentMillis after calling turnr() so period1 will elapse again before period2 and turnr() will be called again

Please explain in words what you want the sketch to do

The robot is supposed to follow an object that is between distance 45 and 125
i want the robot to turn left , brake then turn right, brake when there is not something in that range(as if searching)

Use switch/state with millis() timing in each state to create a "state machine" to move through the required states

Is the robot going to do anything else whilst this is going on ?

it is constantly looking for an object to follow

is there a good tutorial out on the web for this ?

If there is then I don't know where to find it

Are you familiar with using switch/state to selectively execute sections of code depending on the current state of the sketch ?

unfortunately not, I am new to coding

This is far from a tutorial but the example may give you some ideas as to what is possible using switch/state which is really an easy to read variety of if/else

enum states
{
  LED_ON,
  LED_OFF
};

states currentState;
const byte ledPin = 13;

unsigned long periods[] = {1000, 100};

void setup()
{
  Serial.begin(115200);
  pinMode(ledPin, OUTPUT);
  currentState = LED_OFF;
  digitalWrite(ledPin, LOW);
}

void loop()
{
  unsigned long currentTime = millis();
  static unsigned long stateStartTime = currentTime;
  switch (currentState)
  {
    case LED_OFF: //execute the code for this state
      if (currentTime - stateStartTime >= periods[currentState]) //test if period ended
      {
        digitalWrite(ledPin, HIGH); //if so turn on LED
        currentState = LED_ON;  //change current state
        stateStartTime = currentTime; //save time this state started
      }
      break;
    case LED_ON: //execute the code for this state
      if (currentTime - stateStartTime >= periods[currentState]) //test if period ended
      {
        digitalWrite(ledPin, LOW); //if so turn off LED
        currentState = LED_OFF;  //change current state
        stateStartTime = currentTime; //save time this state started
      }
      break;
  };
  //other code goes here but it must not block the execution of loop()
}

The sketch will be in one of 2 states, LED_ON or LED_OFF and the switch/case causes the code appropriate to the current state to be executed. For each case here all it does is to test whether a period of time relevant to the current state has elapsed and, if so, switch to the other state.

Not very exciting and there are shorter ways to do it but it shows some principles

  • only code for the current state is executed
  • the state change occurs as a result of a timing period ending, but see ** below
  • any other non blocking code can be run in loop() outside of the switch/case
  • the program structure is easier to read than if/else because the code blocks are more prominent

** note that there can be more than one exit condition for a case and they can be set outside of the switch/case.

For instance, one state could be turning the robot to the right as part of its obstacle avoidance when a new obstacle is detected in loop() and it needs to abort its current state and start its obstacle avoidance actions again

#define echoPin 10 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 7 //attach pin D3 Arduino to pin Trig of HC-SR04

long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

enum states
{
  LED_ON,
  LED_OFF
};

states currentState;
const byte ledPin = 13;

unsigned long periods[] = {1000, 100};


void setup() {

  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin

  //Setup Channel B
  pinMode(13, OUTPUT); //Initiates Motor Channel A pin
  pinMode(8, OUTPUT);  //Initiates Brake Channel A pin

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");

  pinMode(ledPin, OUTPUT);
  currentState = LED_OFF;
  digitalWrite(ledPin, LOW);

}

//start direction functions

void forward()
{
  //Motor A forward @ full speed
  digitalWrite(12, HIGH);  //Establishes backward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);    //Spins the motor on Channel A at half speed

  //Motor B forward @ full speed
  digitalWrite(13, LOW); //Establishes forward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);   //Spins the motor on Channel B at full speed
}

void brake()
{
  //Motor A stop
  digitalWrite(12, LOW);  //Establishes backward direction of Channel A
  digitalWrite(9, HIGH);   //Disengage the Brake for Channel A
  analogWrite(3, 0);    //Spins the motor on Channel A at half speed

  //Motor B stop
  digitalWrite(13, LOW); //Establishes forward direction of Channel B
  digitalWrite(8, HIGH);   //Disengage the Brake for Channel B
  analogWrite(11, 0);   //Spins the motor on Channel B at full speed
}

void turnr()
{
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  //Motor B backward @ half speed
  digitalWrite(13, HIGH);  //Establishes backward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at half speed
}
void turnl()
{
  digitalWrite(12, LOW); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  //Motor B backward @ half speed
  digitalWrite(13, LOW);  //Establishes backward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at half speed


}

//start loop

void loop() {
  // Clears the trigPin condition
  digitalWrite(trigPin, LOW);
  delayMicroseconds(1);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(2);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  void loop()
  {
    unsigned long currentTime = millis();
    static unsigned long stateStartTime = currentTime;
    switch (currentState)
    {
      case LED_OFF: //execute the code for this state
        if (currentTime - stateStartTime >= periods[currentState]) //test if period ended
        {
          if (distance >= 130)
          {
            brake();

            if (currentMillis - previousmillis >= period)
            {
              turnr();
              previousmillis = currentMillis;
            }

            {
              brake();
              previousmillis = currentMillis;
            }

            {
              turnl();
              previousmillis = currentMillis;
            }

            {
              brake();
              previousmillis = currentMillis;
            }

          }
          else
          {
            forward();
          }
          digitalWrite(ledPin, HIGH); //if so turn on LED
          currentState = LED_ON;  //change current state
          stateStartTime = currentTime; //save time this state started
        }


        break;
      case LED_ON: //execute the code for this state
        if (currentTime - stateStartTime >= periods[currentState]) //test if period ended
        {
          if (distance <= 40)
          {
            brake();

            if (currentMillis - previousmillis >= period)
            {
              turnr();
              previousmillis = currentMillis;
            }

            {
              brake();
              previousmillis = currentMillis;
            }


            {
              turnl();
              previousmillis = currentMillis;
            }

            {
              brake();
              previousmillis = currentMillis;
            }
          }
          else
          {
            forward();
          }
          digitalWrite(ledPin, LOW); //if so turn off LED
          currentState = LED_OFF;  //change current state
          stateStartTime = currentTime; //save time this state started
        }
        break;
    };

  } //end loop

in this line i am getting the error
a function-definition is not allowed here before '{' token

 void loop()
  {
    unsigned long currentTime = millis();

Where does the setup() function end and why have you got two loop() functions in your sketch ?


#define echoPin 10 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 7 //attach pin D3 Arduino to pin Trig of HC-SR04

long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

enum states
{
  LED_ON,
  LED_OFF
};

states currentState;
const byte ledPin = 13;

unsigned long periods[] = {1000, 100};


void setup() {

  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin

  //Setup Channel B
  pinMode(13, OUTPUT); //Initiates Motor Channel A pin
  pinMode(8, OUTPUT);  //Initiates Brake Channel A pin

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");

  pinMode(ledPin, OUTPUT);
  currentState = LED_OFF;
  digitalWrite(ledPin, LOW);

}

//start direction functions

void forward()
{
  //Motor A forward @ full speed
  digitalWrite(12, HIGH);  //Establishes backward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);    //Spins the motor on Channel A at half speed

  //Motor B forward @ full speed
  digitalWrite(13, LOW); //Establishes forward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);   //Spins the motor on Channel B at full speed
}

void brake()
{
  //Motor A stop
  digitalWrite(12, LOW);  //Establishes backward direction of Channel A
  digitalWrite(9, HIGH);   //Disengage the Brake for Channel A
  analogWrite(3, 0);    //Spins the motor on Channel A at half speed

  //Motor B stop
  digitalWrite(13, LOW); //Establishes forward direction of Channel B
  digitalWrite(8, HIGH);   //Disengage the Brake for Channel B
  analogWrite(11, 0);   //Spins the motor on Channel B at full speed
}

void turnr()
{
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  //Motor B backward @ half speed
  digitalWrite(13, HIGH);  //Establishes backward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at half speed
}
void turnl()
{
  digitalWrite(12, LOW); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  //Motor B backward @ half speed
  digitalWrite(13, LOW);  //Establishes backward direction of Channel B
  digitalWrite(8, LOW);   //Disengage the Brake for Channel B
  analogWrite(11, 255);    //Spins the motor on Channel B at half speed


}

//start loop

void loop() {
  // Clears the trigPin condition
  digitalWrite(trigPin, LOW);
  delayMicroseconds(1);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(2);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  {
    unsigned long currentTime = millis();
    static unsigned long stateStartTime = currentTime;
    switch (currentState)
    {
      case LED_OFF: //execute the code for this state
        if (currentTime - stateStartTime >= periods[currentState]) //test if period ended
        {
          if (distance >= 130)
          {
            brake();

            
            {
              turnr();
             
            }

            {
              brake();
             
            }

            {
              turnl();
              
            }

            {
              brake();
             
            }

          }
          else
          {
            forward();
          }
          digitalWrite(ledPin, HIGH); //if so turn on LED
          currentState = LED_ON;  //change current state
          stateStartTime = currentTime; //save time this state started
        }


        break;
      case LED_ON: //execute the code for this state
        if (currentTime - stateStartTime >= periods[currentState]) //test if period ended
        {
          if (distance <= 40)
          {
            brake();
            {
              turnr();
            
            }

            {
              brake();
              
            }


            {
              turnl();
             
            }

            {
              brake();
             
            }
          }
          else
          {
            forward();
          }
          digitalWrite(ledPin, LOW); //if so turn off LED
          currentState = LED_OFF;  //change current state
          stateStartTime = currentTime; //save time this state started
        }
        break;
    };


  }} //end loop

is this better?