DC motors controlled using Ultrasonic sensor

Hi..

I working on a project with 2 IR sensors & Ultrasonic sensor to control 2 DC motors for driving a small obstacle avoiding robot. Using Arduino Mega with Adafruit motorshield. I want it to cover an entire room in a sweeping pattern.

I've written a code in which it moves forward and when the distance from the obstruction is less than 10cm, it takes a right turn. Also if any obstacles are detected by the IR sensors on left or right it moves backward and turns in the opposite direction. Time for 180 degree turn is calculated as 10.4 secs and same is included in Left & Right turn function.

I want the robot to move forward and take a right turn when the Ultrasonic sensor gives reading less than 10cm...

here's where i want the help...next time i need the robot to turn left instead of right..so that it covers the entire room. My code is only for turning right on <10cm condition, I want it to take Left turn next time when <10cm condition is met..then again right turn for the next <10cm condition..

Something like...'if the last turn was right' (triggered by ultrasonic) 'turn left this time' & if the last turn was left, this time turn right.

i'm attaching the code.

Thanks in advance

#include <AFMotor.h>
#include <NewPing.h>

int trigPin = 51;       // Transmit - Trigger
int echoPin = 53;       // Receive - Echo

NewPing sonar(trigPin, echoPin, 200);  // define an utrasonic sensor and name it 'sonar' wih a maximum range of 200cm

int distance;      // For use with ultrasonic sensor in the 'rangeDetect' function below

AF_DCMotor motor1(1, MOTOR12_64KHZ); //AF_DCMotor(motor#, frequency
AF_DCMotor motor2(2, MOTOR12_64KHZ); //AF_DCMotor(motor#, frequency

void setup() {

  motor1.setSpeed(255);  // 255 rpm
  motor2.setSpeed(255);  // 255 rpm
  Serial.begin(9600);//start the serial port at 9600 baud
  pinMode(trigPin, OUTPUT);             // Set socket 51 as output socket
  pinMode(echoPin, INPUT);              // Set socket 53 as an input socket

  pinMode(31, INPUT); //left IR sensor input
  pinMode(41, INPUT); //Right IR Sensor input
}


void loop() {                   // *** The contents of this function will be run repeatedly ***

  if (rangeDetect() > 5 && rangeDetect() < 10) { // When the distance of the nearest is onject is less than 10cm & more than 5cm, move right
    rightStep();

  }
  else {
    forwardStep();

  }

  if (rangeDetect() < 5) { // When the distance of the nearest is onject is less than 5cm & more than 10cm, move Left
    backwardStep();
    rightStep();

  }

  int l1 = digitalRead(31); //left sensor input
  int r1 = digitalRead(41); //Right Sensor Input
  if ((l1 == HIGH) && (r1 == HIGH)) // obstacle on right & left
  {
    backwardStep(); //reverse & right turn
    rightStep();

  } else if ((l1 == LOW) && (r1 == HIGH)) { // obstacle on right

    backwardStep();
    leftStep();
  } else if ((l1 == HIGH) && (r1 == LOW)) { // obstacle on left

    backwardStep();
    rightStep();
  }
  
  
}



//to move the motors forward
void forwardStep() {
  // step one step each forward
  motor1.run(FORWARD);// turn it on going forward
  motor2.run(FORWARD);// turn it on going forward
}

// to move the motors back
void backwardStep() {
  // step one step each backward
  motor1.run(BACKWARD); // turn it on going aft
  motor2.run(BACKWARD); // turn it on going aft
  delay(2000);
}


// to move the motors in opposite directions (left)
void rightStep() {
  // step one step each left
  motor1.run(FORWARD); // turn it on going aft
  motor2.run(RELEASE);// turn it on going forward
  delay(10400);
}


// to move the motors in opposite directions (right)
void leftStep() {
  // step one step each right
  motor2.run(FORWARD);// turn it on going forward
  motor1.run(RELEASE); // turn it on going aft
  delay(10400);
}

// to power down the motor drivers and stop the motors
void allStop() {
  // steppers stop
  motor1.run(RELEASE);
  motor2.run(RELEASE);

}

int rangeDetect() {             // This function is used for determining the distance of any obstacle
  distance = sonar.ping_cm();   // The value is placed in a variable called 'distance'

  Serial.print("Distance: "); //Print text with no carriage return (on my laptop)
  Serial.println(distance);   //Give me a readout then carriage return

  return distance;            // The distance value that was found is sent bak up to the 'rangeDetect' function that called it

}

Make a variable to record the direction turned (lastDirectionTurned) when the turn is called. The next time that you want to turn, check lastDirectionTurned and go the opposite way.

Good day,

thanks for the guidance. I understood the idea. However I'm pretty new in this platform. Could you provide an example or something for recording the last turn executed or similar code..so that I can make changes in my code accordingly.

Create a global variable at the top of your sketch. eg.
bool dirLeft = false;

Create a function to update the direction. eg.

bool changeDirection(){
** dirLeft = ! dirLeft;**
** return dirLeft;**
}

And then when you detect an object you can call the changeDirection function eg.

if(changeDirection()){
** //code to turn LEFT**
} else {
** //code to turn RIGHT**
}

There are many ways to do this, but this is one way.

Thanx a lot. It worked well as per my requirement

Create a function to update the direction. eg.

bool changeDirection(){
dirLeft = ! dirLeft;
return dirLeft;
}

There is no particular reason for the function to return a global variable. The value would be available if the function returned nothing.

That is true.