Hey, I am trying to build an obstacle avoiding robot but when i make my robot run it really has trouble with the directions ive gave it. since im using more than one sensor the functions attached to each sensor are overriding each other and the robot doesent know what action to do. Can someone help me fix my if statements because they seem to be contradicting each other.
//In this project, we will be using 4 ultrasonic ranging
//sensors to control the direction of the motor and drive of the motor.
#include <Servo.h>
#include <NewPing.h> // don't forget to include the NewPing library.
#define SONAR_NUM 3
Servo servoDrive; // Define left servo
Servo servoDirection; // Define right servo
NewPing SonarFront(11, 10, 400);// In the project, this was the sensor that
//was used on the right side of the breadboard
NewPing SonarLeft(7, 6, 400);// In the project, this was the sensor that
//was used on the left side of the breadboard
NewPing SonarRight(42, 43, 400);// In the project, this was the sensor that
//was used on the right side of the breadboard
void setup() {
servoDrive.attach(18); // Set left servo to digital pin 10
servoDirection.attach(14); // Set right servo to digital pin 9
}
void loop()
{
unsigned int uS1 = SonarFront.ping(); // activates the first sensor
delay(50); // wait 10ms
unsigned int uS2 = SonarRight.ping(); // activates the third sensor
delay(50); // wait 10ms
unsigned int uS3 = SonarLeft.ping(); // activate the second sensor
delay(50); // wait 10ms
// We will declare "if" statements to control the relay module,
// which controls the motor.
if (uS1 / US_ROUNDTRIP_CM < 10 ) { //if an object is less than 20 cm away
//from the Front sensor,
servoDrive.write(0);
servoDirection.write(180);
//the motor will rotate backwards.
Serial.println("Object detected in front of me.....moving back");
} else {
servoDrive.write(180);
servoDirection.write(90);
//the motor will rotate backwards.
}
if (uS2 / US_ROUNDTRIP_CM < 10) { //if an object is less than 20 cm away
//from the right sensor,
servoDrive.write(180);
servoDirection.write(180);
Serial.println("Object detected to the RIGHT.....moving to the left");
//the motor will rotate left
}
if (uS3 / US_ROUNDTRIP_CM < 10) { //if an object is less than 20 cm away
//from the left sensor,
servoDrive.write(180);
servoDirection.write(0);
Serial.println("Object detected to the LEFT.....moving to the right");
//the motor will rotate right
}
}