Obstacle Avoiding Robot Help

Can't figure this out....tried a bunch of different things.
I want it to move forward until the sensor sees an object, then stop, look both ways, pick the longest route, turn, then continue forward.
I feel like the sensor isn't working. I'm using 6 AA batteries hooked up to the motor shield's external power.
I copied most of this code from other examples on other OA robots but the code never fully worked right for me so I've somewhat made it my own. I almost had it working right but it was a bit too fast and didn't respond to walls in time and when I tried to fine tune it I somehow lost my previous code and screwed everything all up. Now I'm pretty much back to square one.
(Also the wheels move way too fast for my liking but I can't seem to slow them down by playing with motor.setSpeed. Only the voltage seems to make a difference on motor speed.)

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

#define TRIG_PIN A4 //Pin A4 to Ultrasonic Sensor
#define ECHO_PIN A5 //Pin A5 to Ultrasonic Sensor
#define MAX_DISTANCE 200 // Maximum Sensor Distance 200cm
#define COLL_DIST 20 //set distance of stop and reverse to 20cm
#define TURN_DIST 40 // sets distance that robot veers from objects to 40cm
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE); //Set up sensor library to correct pins to measure distance
Servo servo;
AF_DCMotor motor1(1); //Left Wheel
AF_DCMotor motor2(2); //Right Wheel

int leftDistance, rightDistance; //distances on either side
int curDist = 0;
String motorSet ="";
int speedSet = 0;


//-----------------------------------------------------------------------

void setup()
{
  servo.attach(9); 
  servo.write(90); //Set Servo to 90 degrees//facing forward
  delay(500);

}

//-----------------------------------------------------------------------

void loop() 
{
  
  servo.write(90); //sensor forward
  delay(100);
  curDist = readPing(); //read distance

  if (curDist>COLL_DIST){
    changePath();
  } //if forward is blocked, change direction
    moveForward(); //move forward for 1/2 second
  delay(500);
}
//===========================================

void changePath(){
  moveStop();
  servo.write(36); //check right distance
  delay(500);
  rightDistance = readPing(); //set right distance
  delay(500);
  servo.write(144); //check left distance
  delay(700);
  leftDistance = readPing(); //set left distance
  delay(500);
  servo.write(90); //center servo
  delay(100);
  compareDistance();
}

//++++++++++++++++++++++++++++++++++++++++++++++

void compareDistance() //find longest distance
{
  if (leftDistance>rightDistance)
  {
    turnLeft();
  }
  else if (rightDistance>leftDistance)
  {
    turnRight();
  }
  else
  {
    turnAround();
  }
}

//=============================================
int readPing() //read Ultrasonic Sensor
{
  delay(70);
  int uS = sonar.ping();
  int cm = uS/US_ROUNDTRIP_CM;
  return cm;
}

//============================================

void moveStop()  //Stop motors
{
  motor1.run(RELEASE);
  motor2.run(RELEASE);
}

//=============================================

void moveForward()
{
  motorSet = "FORWARD";
  motor1.run(FORWARD);
  motor2.run(FORWARD);
 

    motor1.setSpeed(100);
    motor2.setSpeed(100);
    


}

//=============================================

void moveBackward()
{
  motorSet = "BACKWARD";
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);

    motor1.setSpeed(50);
    motor2.setSpeed(50);
    delay(10);

  
}

//=============================================

void turnRight()
{
  motorSet = "RIGHT";
  motor1.run(FORWARD);
  motor2.run(BACKWARD);
  delay(400);
  motorSet = "FORWARD";
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

//===============================================

void turnLeft()
{
  motorSet = "LEFT";
  motor1.run(BACKWARD);
  motor2.run(FORWARD);
  delay(400);
  motorSet = "FORWARD";
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

//==================================================

void turnAround()
{
  motorSet = "RIGHT";
  motor1.run(FORWARD);
  motor2.run(BACKWARD);
  delay(800);
  motorSet = "FORWARD";
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

The original code that I copied had a speed formula that I changed because it wasn't working right and I had no idea how to make sense of it.

for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet+MAX_SPEED_OFFSET);
    delay(5);

This was on forward and back. Wouldn't the wheels need to be the same speed for forward and back?
Originally when I used this person's code only one motor would work and my bot just went in a circle.

EDIT

Multimeter is showing about 8.4V right now
Dunno if that would help figure out the problem or not.

This was on forward and back. Wouldn't the wheels need to be the same speed for forward and back?

No - one motor needs to go clock wise and the other anti-clockwise. Look at how the motors are mounted. The same is true for a car!.

Mark

No - one motor needs to go clock wise and the other anti-clockwise. Look at how the motors are mounted. The same is true for a car!.

?
Wouldn't that make it spin in a circle?
You mean how they're wired? Like the left wheel (ground, positive) then right (positive, ground?)
Again...when I did that and I put in motor.run(FORWARD); it causes one to spin backward, so I switched them around.
Can you explain that a bit more?

Here.This is the original code I copied. MOTOR12_1KHZ makes one wheel not run for me. I can't figure out why but when I remove it it just goes forward once, then spins, then repeats. I feel like the sensor isn't sensing.
Got this code from http://letsmakerobots.com/node/36657

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

#define TRIG_PIN A4 // Pin A4 on the Motor Drive Shield soldered to the ultrasonic sensor
#define ECHO_PIN A5 // Pin A5 on the Motor Drive Shield soldered to the ultrasonic sensor
#define MAX_DISTANCE 200 // sets maximum useable sensor measuring distance to 200cm
#define MAX_SPEED 180 // sets speed of DC traction motors to 180/256 or about 70% of full speed - to get power drain down.
#define MAX_SPEED_OFFSET 40 // this sets offset to allow for differences between the two DC traction motors ****** from 20
#define COLL_DIST 10 // sets distance at which robot stops and reverses to 10cm
#define TURN_DIST COLL_DIST+10 // sets distance at which robot veers away from object (not reverse) to 20cm (10+10)
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE); // sets up sensor library to use the correct pins to measure distance.

AF_DCMotor motor1(1, MOTOR12_1KHZ); // create motor #1 using M1 output on Motor Drive Shield, set to 1kHz PWM frequency
AF_DCMotor motor2(2, MOTOR12_1KHZ); // create motor #2, using M2 output, set to 1kHz PWM frequency
Servo myservo;  // create servo object to control a servo

int leftDistance, rightDistance; //distances on either side
int curDist = 0;
String motorSet = "";
int speedSet = 0;



void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 (SERVO_2 on the Motor Drive Shield to the servo object
  myservo.write(90); // tells the servo to position at 90-degrees ie. facing forward.
  delay(1000); // delay for one seconds
}

void loop() {
  myservo.write(90);  // move eyes forward
  delay(90);
  curDist = readPing();   // read distance
  if (curDist < COLL_DIST) {
    changePath();
  }  // if forward is blocked change direction
  moveForward();  // move forward for 1/2 second
  delay(500);
}

void changePath() {
  moveStop();   // stop forward movement
  myservo.write(36);  // check distance to the right
  delay(500);
  rightDistance = readPing(); //set right distance
  delay(500);
  myservo.write(144);  // check distace to the left
  delay(700);
  leftDistance = readPing(); //set left distance
  delay(500);
  myservo.write(90); //return to center
  delay(100);
  compareDistance();
}


void compareDistance()   // find the longest distance
{
  if (leftDistance>rightDistance) //if left is less obstructed
  {
    turnLeft();
  }
  else if (rightDistance>leftDistance) //if right is less obstructed
  {
    turnRight();
  }
  else //if they are equally obstructed
  {
    turnAround();
  }
}

int readPing() { // read the ultrasonic sensor distance
  delay(70);  
  unsigned int uS = sonar.ping();
  int cm = uS/US_ROUNDTRIP_CM;
  return cm;
}

void moveStop() {
  motor1.run(RELEASE); 
  motor2.run(RELEASE);
}  // stop the motors.

void moveForward() {
  motorSet = "FORWARD";
  motor1.run(FORWARD);      // turn it on going forward
  motor2.run(FORWARD);      // turn it on going forward
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet+MAX_SPEED_OFFSET);
    delay(5);
  }
}


void moveBackward() {
  motorSet = "BACKWARD";
  motor1.run(BACKWARD);      // turn it on going forward
  motor2.run(BACKWARD);     // turn it on going forward
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet+MAX_SPEED_OFFSET);
    delay(5);
  }
}  

void turnRight() {
  motorSet = "RIGHT";
  motor1.run(FORWARD);      // turn motor 1 forward
  motor2.run(BACKWARD);     // turn motor 2 backward
  delay(400); // run motors this way for 400ms
  motorSet = "FORWARD";
  motor1.run(FORWARD);      // set both motors back to forward
  motor2.run(FORWARD);     
}  

void turnLeft() {
  motorSet = "LEFT";
  motor1.run(BACKWARD);     // turn motor 1 backward
  motor2.run(FORWARD);      // turn motor 2 forward
  delay(400); // run motors this way for 400ms
  motorSet = "FORWARD";
  motor1.run(FORWARD);      // turn it on going forward
  motor2.run(FORWARD);      // turn it on going forward
}  

void turnAround() {
  motorSet = "RIGHT";
  motor1.run(FORWARD);      // turn motor 1 forward
  motor2.run(BACKWARD);     // turn motor 2 backward
  delay(800); // run motors this way for 800ms
  motorSet = "FORWARD";
  motor1.run(FORWARD);      // set both motors back to forward
  motor2.run(FORWARD);     
}

Multimeter is showing about 8.4V right now
Dunno if that would help figure out the problem or not.

Where ? (across the 9V battery pack ?)
AA batteries have an amp hour rating of about 1.0 +/- 0.3 Ah.
You didn't post any motor information so we don't know the voltage and current rating of your motors but AA batteries (in series ONLY) will not last very long driving motors, especially if the motors get loaded down by trying to drive against a wall or something like that.
8.4V is only 0.6V below 9.0 volts so without knowing how long the batteries were in use before this measurement this information does not tell us much.

1 amp hour will drive a load that draws one amp for one hour , or a load that draws 1/10th A for 10 hours , or a load that draws 1/20th amp for 20 hours.

I don't know how to determine how many amp hours have been discharged based on the 0.6 Ah (decrease ) reduction in battery voltage.
If you run the motors at full throttle (both motors), and keep track of the time, if it ran for one hour and then stopped, that would mean that each motor is drawing 1/2 A (500 mA).

You got a lot of problems going on here. First off how are you driving the wheels ?
If your using two motors to move forward one side turns CW and one turns CCW but that can be fixed in the wiring of the motor.
Or handled in code.
Next thing you need to figure is ok im moving forward at high speed going to hit a wall how long does it take to stop before that happens.
We have to act on that to do one of two things low down or stop then figure new path to take in your case stop looks like what you want.
Then figure new path.

To help with the code need to see how you have it wired..

Well its a Mega 2560 with a DK electronics motor shield.
I have a 6AA battery pack connected to external power, motor 1 connected to M1 and motor 2 to M2, Servo to servo_2, and the ultrasonic sensor to to 5v, grnd, and A8 and A9.
Not sure really how to explain it other than that.
I'll try taking some pics but all I have is a webcam.

Main thing I don't understand is when I use this person's code the right wheel doesn't move at all. Unless I delete "MOTOR12_1KHZ".

So you said there's a lot wrong with the code. Here's what I have. I've changed it a hundred times a hundred different ways and always end up back at the beginning starting over. Here's what I have. What's the deal? I've changed the wiring around quite a bit and the only difference it seems to make is what direction the wheels go with FORWARD or BACKWARD.

/*
Rover Prototype
*/

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

#define TRIG_PIN A8 // Pin A4 on the Motor Drive Shield soldered to the ultrasonic sensor
#define ECHO_PIN A9 // Pin A5 on the Motor Drive Shield soldered to the ultrasonic sensor
#define MAX_DISTANCE 200 // sets maximum useable sensor measuring distance to 200cm
#define MAX_SPEED 180 // sets speed of DC traction motors to 180/256 or about 70% of full speed - to get power drain down.
#define MAX_SPEED_OFFSET 40 // this sets offset to allow for differences between the two DC traction motors ****** from 20
#define COLL_DIST 20 // sets distance at which robot stops and reverses to 10cm
#define TURN_DIST COLL_DIST+10 // sets distance at which robot veers away from object (not reverse) to 20cm (10+10)
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE); // sets up sensor library to use the correct pins to measure distance.

AF_DCMotor motor1(1, MOTOR12_1KHZ); // create motor #1 using M1 output on Motor Drive Shield, set to 1kHz PWM frequency
AF_DCMotor motor2(2); // create motor #2, using M2 output, set to 1kHz PWM frequency
Servo myservo;  // create servo object to control a servo

int leftDistance, rightDistance; //distances on either side
int curDist;
String motorSet = "";
int speedSet = 0;

//-------------------------------------------- SETUP LOOP ----------------------------------------------------------------------------
void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 (SERVO_2 on the Motor Drive Shield to the servo object
  myservo.write(90); // tells the servo to position at 90-degrees ie. facing forward.
  delay(1000); // delay for one seconds
 }
//------------------------------------------------------------------------------------------------------------------------------------

//---------------------------------------------MAIN LOOP ------------------------------------------------------------------------------
void loop() {
  myservo.write(90);  // move eyes forward
  delay(90);
  curDist = readPing();   // read distance
  moveForward();  // move forward for 1/2 second
  if (curDist < COLL_DIST) {changePath();}  // if forward is blocked change direction
  
 }
//-------------------------------------------------------------------------------------------------------------------------------------

void changePath() {
  moveStop();   // stop forward movement
  myservo.write(0);  // check distance to the right
    delay(500);
    rightDistance = readPing(); //set right distance
    delay(500);
    myservo.write(179);  // check distace to the left
    delay(700);
    leftDistance = readPing(); //set left distance
    delay(500);
    myservo.write(90); //return to center
    delay(100);
    compareDistance();
  }

 
void compareDistance()   // find the longest distance
{
  if (leftDistance>rightDistance) //if left is less obstructed
  {
    turnLeft();
  }
  else if (rightDistance>leftDistance) //if right is less obstructed
  {
    turnRight();
  }
   else //if they are equally obstructed
  {
    turnAround();
  }
}


//-------------------------------------------------------------------------------------------------------------------------------------

int readPing() { // read the ultrasonic sensor distance
  delay(70);  
  unsigned int uS = sonar.ping();
  int cm = uS/US_ROUNDTRIP_CM;
  return cm;
}
//-------------------------------------------------------------------------------------------------------------------------------------
void moveStop() {motor1.run(RELEASE); motor2.run(RELEASE);}  // stop the motors.
//-------------------------------------------------------------------------------------------------------------------------------------
void moveForward() {
    motorSet = "FORWARD";
    motor1.run(FORWARD);      // turn it on going forward
    motor2.run(FORWARD);      // turn it on going forward
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet+MAX_SPEED_OFFSET);
    delay(5);
  }
}
//-------------------------------------------------------------------------------------------------------------------------------------
void moveBackward() {
    motorSet = "BACKWARD";
    motor1.run(BACKWARD);      // turn it on going forward
    motor2.run(BACKWARD);     // turn it on going forward
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet+MAX_SPEED_OFFSET);
    delay(5);
  }
} 
//-------------------------------------------------------------------------------------------------------------------------------------
void turnRight() {
  motorSet = "RIGHT";
  motor1.run(FORWARD);      // turn motor 1 forward
  motor2.run(BACKWARD);     // turn motor 2 backward
  delay(400); // run motors this way for 400ms
  motorSet = "FORWARD";
  motor1.run(FORWARD);      // set both motors back to forward
  motor2.run(FORWARD);     
} 
//-------------------------------------------------------------------------------------------------------------------------------------
void turnLeft() {
  motorSet = "LEFT";
  motor1.run(BACKWARD);     // turn motor 1 backward
  motor2.run(FORWARD);      // turn motor 2 forward
  delay(400); // run motors this way for 400ms
  motorSet = "FORWARD";
  motor1.run(FORWARD);      // turn it on going forward
  motor2.run(FORWARD);      // turn it on going forward
} 
//-------------------------------------------------------------------------------------------------------------------------------------
void turnAround() {
  motorSet = "RIGHT";
  motor1.run(FORWARD);      // turn motor 1 forward
  motor2.run(BACKWARD);     // turn motor 2 backward
  delay(800); // run motors this way for 800ms
  motorSet = "FORWARD";
  motor1.run(FORWARD);      // set both motors back to forward
  motor2.run(FORWARD);     
}

Is there any way you guys can just give me a working code?
I don't learn very well through reading. Especially terms I don't understand that are explained by more terms I don't understand. It would greatly help me to see a working code and analyze it and break it down.
As for this code, it seems fairly understandable to me, it just doesn't work. Only part I don't really understand is the int readPing() part. Like the US_ROUNDTRIP_CM. I don't get that at all. I never defined ROUNDTRIP. Why does this work and why can't I just say leftDistance = sonar.ping(); or rightDistance = sonar.ping();?

asdsadsa.jpg

Snapshot_20140825_1.jpg

Snapshot_20140825_2.jpg

Snapshot_20140825_3.jpg

void loop() {
  myservo.write(90);  // move eyes forward
  delay(90);
  curDist = readPing();   // read distance
  moveForward();  // move forward for 1/2 second
  if (curDist < COLL_DIST) {changePath();}  // if forward is blocked change direction
  
 }

Look straight ahead. Measure the distance. Go forward, even if you are butting up against a wall. Then, turn if the distance is small.

Why? When you are walking, do you close your eyes, walk for half a second, then open your eyes? That is what your robot is doing.

But, forget all that for now. Does moveForward() make the robot move correctly? If not, NOTHING else in the code matters because you have a hardware problem.

Yes it does move forward with moveForward();
problem is I'm having trouble making moveForward work when it should. How do I tell it to judge distance without "closing it's eyes" as you say?

EDIT

Hey I think you helped me figure it out.
I changed it to this.

void loop() {
  myservo.write(90);  // move eyes forward
  delay(90);
  curDist = readPing();   // read distance
  if (curDist > COLL_DIST) 
  {
    moveForward();
  if (curDist < COLL_DIST) {changePath();}  // if forward is blocked change direction
  }
  else {changePath();}

 }

Seems to be working but it's still too fast for the sensor and it hits walls, then stops. I'll adjust the setSpeed or decrease the battery quantity and see how that works. Thanks. It's responding much better now.

I'm doing an obstacle avoiding car with an arduino uno r3 board, hc-sr04 ultrasonic sensor, dual h-bridge l298 and sg90 microservo.

My code doesn't work, can anyone tell me what i'm doing wrong?

#define MOTOR1_CTL1  8  // I1  
#define MOTOR1_CTL2  9  // I2  
#define MOTOR1_PWM   11 // EA  
  
#define MOTOR2_CTL1  6  // I3  
#define MOTOR2_CTL2  7  // I4  
#define MOTOR2_PWM   10 // EB  
  
#define MOTOR_DIR_FORWARD  0  
#define MOTOR_DIR_BACKWARD   1  

#include <Servo.h>
 
Servo myservo;  
 
int pos = 0; 
int frontal;
int dreta;
int esquerra;
  
void setup()  
{  
   
   pinMode(MOTOR1_CTL1,OUTPUT);  
   pinMode(MOTOR1_CTL2,OUTPUT);  
   pinMode(MOTOR1_PWM,OUTPUT);  
     
  // Setup pins for motor 2  
   pinMode(MOTOR2_CTL1,OUTPUT);  
   pinMode(MOTOR2_CTL2,OUTPUT);  
   pinMode(MOTOR2_PWM,OUTPUT);  

   myservo.attach(3);  
   
   motorStart(1, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
  setSpeed(1, 0);     // velocitat 0-255
  motorStart(2, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
  setSpeed(2, 0);     // velocitat 0-255
  
   myservo.write(80);  // situem el servo al centre 
}  
  
void setSpeed(char motor_num, char motor_speed)  
{  
   if (motor_num == 1)  
   {  
      analogWrite(MOTOR1_PWM, motor_speed);  
   }     
   else  
   {  
      analogWrite(MOTOR2_PWM, motor_speed);  
   }  
}  
  
void motorStart(char motor_num, byte direccio)  
{  
    
   char pin_ctl1;  
   char pin_ctl2;  
     
   if (motor_num == 1)  
   {  
      pin_ctl1 = MOTOR1_CTL1;  
      pin_ctl2 = MOTOR1_CTL2;  
   }     
   else  
   {  
      pin_ctl1 = MOTOR2_CTL1;  
      pin_ctl2 = MOTOR2_CTL2;       
   }  
    
   switch (direccio)  
   {  
     case MOTOR_DIR_FORWARD:  
     {  
       digitalWrite(pin_ctl1,LOW);  
       digitalWrite(pin_ctl2,HIGH);            
     }  
     break;   
            
     case MOTOR_DIR_BACKWARD:  
     {  
        digitalWrite(pin_ctl1,HIGH);  
        digitalWrite(pin_ctl2,LOW);            
     }  
     break;           
   }  
}  
  
void motorStop(char motor_num)  
{  
   setSpeed(motor_num, 0);  
   if (motor_num == 1)  
   {  
     digitalWrite(MOTOR1_CTL1,HIGH);  
     digitalWrite(MOTOR1_CTL2,HIGH);       
   }  
   else  
   {  
     digitalWrite(MOTOR2_CTL1,HIGH);  
     digitalWrite(MOTOR2_CTL2,HIGH);       
   }  
}  
 

void loop()  
{ 
  //motors endavant
  motorStart(1, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
  setSpeed(1, 200);     // velocitat 0-255
  motorStart(2, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
  setSpeed(2, 200);     // velocitat 0-255
  
  //llegim sensor
  frontal =analogRead(3);
  if(frontal < 20)
  {
      motorStart(1, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
      setSpeed(1, 0);     // velocitat 0-255
      motorStart(2, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
      setSpeed(2, 0);     // velocitat 0-255
      
      myservo.write(135);
      esquerra =analogRead(3);
      myservo.write(35);
      dreta =analogRead(3);
      if( dreta > esquerra)
      {
         motorStart(1, 0);
         setSpeed(1, 200);
         motorStart(2, 1);
         setSpeed(2, 200);
         
      }
      else
      {
        motorStart(1, 1);
        setSpeed(1, 200);
        motorStart(1, 0);
        setSpeed(1, 200);
      }
  }
  
  
  
  
  
  
 
  else
  {
    motorStart(1, 1);
    setSpeed(1, 200);
    motorStart(2, 0);
    setSpeed(2, 200);
    delay(500);
  }
}

Thank you guys!

I'm doing an obstacle avoiding car with an arduino uno r3 board, hc-sr04 ultrasonic sensor, dual h-bridge l298 and sg90 microservo.

My code doesn't work, can anyone tell me what i'm doing wrong?

#define MOTOR1_CTL1  8  // I1  
#define MOTOR1_CTL2  9  // I2  
#define MOTOR1_PWM   11 // EA  
  
#define MOTOR2_CTL1  6  // I3  
#define MOTOR2_CTL2  7  // I4  
#define MOTOR2_PWM   10 // EB  
  
#define MOTOR_DIR_FORWARD  0  
#define MOTOR_DIR_BACKWARD   1  

#include <Servo.h>
 
Servo myservo;  
 
int pos = 0; 
int frontal;
int dreta;
int esquerra;
  
void setup()  
{  
   
   pinMode(MOTOR1_CTL1,OUTPUT);  
   pinMode(MOTOR1_CTL2,OUTPUT);  
   pinMode(MOTOR1_PWM,OUTPUT);  
     
  // Setup pins for motor 2  
   pinMode(MOTOR2_CTL1,OUTPUT);  
   pinMode(MOTOR2_CTL2,OUTPUT);  
   pinMode(MOTOR2_PWM,OUTPUT);  

   myservo.attach(3);  
   
   motorStart(1, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
  setSpeed(1, 0);     // velocitat 0-255
  motorStart(2, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
  setSpeed(2, 0);     // velocitat 0-255
  
   myservo.write(80);  // situem el servo al centre 
}  
  
void setSpeed(char motor_num, char motor_speed)  
{  
   if (motor_num == 1)  
   {  
      analogWrite(MOTOR1_PWM, motor_speed);  
   }     
   else  
   {  
      analogWrite(MOTOR2_PWM, motor_speed);  
   }  
}  
  
void motorStart(char motor_num, byte direccio)  
{  
    
   char pin_ctl1;  
   char pin_ctl2;  
     
   if (motor_num == 1)  
   {  
      pin_ctl1 = MOTOR1_CTL1;  
      pin_ctl2 = MOTOR1_CTL2;  
   }     
   else  
   {  
      pin_ctl1 = MOTOR2_CTL1;  
      pin_ctl2 = MOTOR2_CTL2;       
   }  
    
   switch (direccio)  
   {  
     case MOTOR_DIR_FORWARD:  
     {  
       digitalWrite(pin_ctl1,LOW);  
       digitalWrite(pin_ctl2,HIGH);            
     }  
     break;   
            
     case MOTOR_DIR_BACKWARD:  
     {  
        digitalWrite(pin_ctl1,HIGH);  
        digitalWrite(pin_ctl2,LOW);            
     }  
     break;           
   }  
}  
  
void motorStop(char motor_num)  
{  
   setSpeed(motor_num, 0);  
   if (motor_num == 1)  
   {  
     digitalWrite(MOTOR1_CTL1,HIGH);  
     digitalWrite(MOTOR1_CTL2,HIGH);       
   }  
   else  
   {  
     digitalWrite(MOTOR2_CTL1,HIGH);  
     digitalWrite(MOTOR2_CTL2,HIGH);       
   }  
}  
 

void loop()  
{ 
  //motors endavant
  motorStart(1, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
  setSpeed(1, 200);     // velocitat 0-255
  motorStart(2, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
  setSpeed(2, 200);     // velocitat 0-255
  
  //llegim sensor
  frontal =analogRead(3);
  if(frontal < 20)
  {
      motorStart(1, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
      setSpeed(1, 0);     // velocitat 0-255
      motorStart(2, 1);     //canvivi de direccio 1 endavant - 0 endarrera   
      setSpeed(2, 0);     // velocitat 0-255
      
      myservo.write(135);
      esquerra =analogRead(3);
      myservo.write(35);
      dreta =analogRead(3);
      if( dreta > esquerra)
      {
         motorStart(1, 0);
         setSpeed(1, 200);
         motorStart(2, 1);
         setSpeed(2, 200);
         
      }
      else
      {
        motorStart(1, 1);
        setSpeed(1, 200);
        motorStart(1, 0);
        setSpeed(1, 200);
      }
  }
  
  
  
  
  
  
 
  else
  {
    motorStart(1, 1);
    setSpeed(1, 200);
    motorStart(2, 0);
    setSpeed(2, 200);
    delay(500);
  }
}

Thank you guys!

Is this how you are you are trying to take a reading from the HC-SR04?

frontal =analogRead(3);

This won't work. Take a look at the code sample on this page:

http://superawesomerobots.com/tutorials/hc-sr04-tutorial-for-arduino/

This sensor must be connected to two digital pins. You need to set the TRIGGER pin HIGH for 10 microseconds then set it back to LOW and then use pulseIn() to take a reading from the ECHO pin.

pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
int distance = pulseIn(echoPin, HIGH) / 2;

Hope that helps.

You can't use Servo with PWM (they both try to use the same timer.) Take a look at SofServo.

Mark

Use an AC/DC converter so there wouldn't be any problem about low current or vehicle's high weight .
And I suppose using multiple sensors would be easier than programming it to spin , just give some if codes so it'd go to the direction of the sensor with highest distance .
And noteworthy , ultrasonics make mistakes in very low or very far distances .