obstacle avoiding robot, help with code

hi could someone please help,

i am making a robot that manourves away from obstacles, my first code which makes the robot move forwards and if anything was in the way it will stop, then rotates the servo from left to right, but now that i want it to turn left or right it wouldn't work, can some on please help me

as the teacher know that i have just started this, i would need a basic code: the last code
the first code is the drive forward and stop if obstacle detected

const int pingPin =8 ;
int motorpin1 = 3;                  //define digital output pin no.

int motorpin2 = 4;                  //define digital output pin no.

int motorpin3 = 5;

int motorpin4 = 6;
#include <Servo.h>
 
Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created
 
int pos = 0; 



void setup()    // function which runs once
{ 
  Serial.begin(9600);   // initialize the data rate in bits per second
myservo.attach(9);


} 
void loop()         // function which will run continuously
{ 
  long duration, inches, cm;  //  function from datasheet of ping sensor
  pinMode(pingPin,OUTPUT);    //  
  digitalWrite(pingPin,LOW); 
  delayMicroseconds(2);       // delay recomended from datasheet
  digitalWrite(pingPin,HIGH); 
  delayMicroseconds(5);       // delay recomended from datasheet
  digitalWrite(pingPin,LOW); 
  pinMode(pingPin,INPUT); 
  duration =pulseIn(pingPin,HIGH); 
  
  inches = microsecondsToInches(duration); // converting time into distance
  cm = microsecondsToCentimeters(duration); 
  
  Serial.print(inches); 
  Serial.print("in, "); 
  Serial.print(cm); 
  Serial.print("cm"); 
  Serial.println(); 
  
  delay(100); 
 { 

   if (inches <= 2) // if there is an obstacle at 15 inches or below
 {

   digitalWrite(motorpin1,LOW);

  digitalWrite(motorpin2,LOW);

  digitalWrite(motorpin3, LOW);

  digitalWrite(motorpin4, LOW);
 
 
 
   for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {                                
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);  
  }
 }
 
  else                       
{ 
  
  digitalWrite(motorpin1,LOW);

  digitalWrite(motorpin2,HIGH);

  digitalWrite(motorpin3,HIGH);

  digitalWrite(motorpin4,LOW);   
    }
  }
} 

long microsecondsToInches(long microseconds) 

{ 

  return microseconds / 74 / 2;  

}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

and this is meant to be the final code, please help me =(

#include <Servo.h>                                  //includes the servo library

int motorPin1 = 3;
int motorPin2 = 4;
int motorPin3 = 5;
int motorPin4 = 6;
int servoPin = 9;

const int pingPin = 8;
const int dist = 0;

int leftdist = 0;
int rightdist = 0;
int object = 10;             //distance at which the robot should look for another route                           

Servo myservo;

void setup ()
{
  Serial.begin(9600);   // initialize the data rate in bits per second
  myservo.attach(9);
  pinMode(motorPin1,OUTPUT);
  pinMode(motorPin2,OUTPUT);
  pinMode(motorPin3,OUTPUT);
  pinMode(motorPin4,OUTPUT);
  myservo.attach(servoPin);
  myservo.write(90);
  delay(700);
}
void loop()
{
   

 
   
  if(dist < object) {                         //if distance is less than 5
   forward();                                  //then move forward
  }
  if(dist >= object) {               //if distance is greater than or equal to 5
    findroute();
  }
}
 
void forward() {                         
   digitalWrite(motorPin1,HIGH );
   digitalWrite(motorPin2,LOW);
   digitalWrite(motorPin3,HIGH);
   digitalWrite(motorPin4,LOW);
   return;
 }
 
void findroute() {
  halt();                                             // stop
  reverse();                                       //go backwards
  lookleft();                                      //go to subroutine lookleft
  lookright();                                   //go to subroutine lookright
                                      
  if ( leftdist < rightdist )
  {
    turnleft();
  }
 else
 {
   turnright ();
 }
}

void backward() {
  digitalWrite(motorPin1,LOW);
  digitalWrite(motorPin2,HIGH);
  digitalWrite(motorPin3,LOW);
  digitalWrite(motorPin4,HIGH);
  delay(500);
  halt();
  return;
}

void halt () {
  digitalWrite(motorPin1,LOW);
  digitalWrite(motorPin2,LOW);
  digitalWrite(motorPin3,LOW);
  digitalWrite(motorPin4,LOW);
  delay(500);                          //wait after stopping
  return;
}
 
void lookleft() {
  myservo.write(150);
  delay(700);                                //wait for the servo to get there
  leftdist = digitalRead(pingPin);
  myservo.write(90);
  delay(700);                                 //wait for the servo to get there
  return;
}

void lookright () {
  myservo.write(30);
  delay(700);                           //wait for the servo to get there
  rightdist = digitalRead(pingPin);
  myservo.write(90);                                  
  delay(700);                        //wait for the servo to get there
  return;
}

void turnleft () {
  digitalWrite(motorPin1,HIGH);       //use the combination which works for you
  digitalWrite(motorPin2,LOW);      //right motor rotates forward and left motor backward
  digitalWrite(motorPin3,LOW);
  digitalWrite(motorPin4,HIGH);
  delay(1000);                     // wait for the robot to make the turn
  halt();
  return;
}

void turnright () {
  digitalWrite(motorPin1,LOW);       //use the combination which works for you
  digitalWrite(motorPin2,HIGH);    //left motor rotates forward and right motor backward
  digitalWrite(motorPin3,HIGH);
  digitalWrite(motorPin4,LOW);
  delay(1000);                              // wait for the robot to make the turn
  halt();
  return;
}
long duration, inches, cm;  //  function from datasheet of ping sensor
  pinMode(pingPin,OUTPUT);    //  
  digitalWrite(pingPin,LOW); 
  delayMicroseconds(2);       // delay recomended from datasheet
  digitalWrite(pingPin,HIGH); 
  delayMicroseconds(5);       // delay recomended from datasheet
  digitalWrite(pingPin,LOW); 
  pinMode(pingPin,INPUT); 
  duration =pulseIn(pingPin,HIGH); 
  
  inches = microsecondsToInches(duration); // converting time into distance
  cm = microsecondsToCentimeters(duration); 
  
  Serial.print(inches); 
  Serial.print("in, "); 
  Serial.print(cm); 
  Serial.print("cm"); 
  Serial.println(); 
  
  delay(100);

long microsecondsToInches(long microseconds) 

{ 
  return microseconds / 74 / 2;  

}

long microsecondsToCentimeters(long microseconds)

{
 
  return microseconds / 29 / 2;
}

please please will need some one to help or tell me where im going wrong

please please will need some one to help or tell me where im going wrong

#7 below has some of what you need.

http://arduino.cc/forum/index.php/topic,148850.0.html

sorry

What are you using for motors here, and a motor shield? It's a little difficult to know
how to command the motor, given the code shown. Normally, you want to control
motor speeds, rather than just turn them off or on fully.

Your new code shows better modularization, but you didn't wrap the ping code in
a function. You should put the global variables at the top of the source file.

long duration, inches, cm;  //  function from datasheet of ping sensor

void read_Ping( void )
{
  pinMode(pingPin,OUTPUT);    //  
  digitalWrite(pingPin,LOW); 
  delayMicroseconds(2);       // delay recomended from datasheet
  digitalWrite(pingPin,HIGH); 
  delayMicroseconds(5);       // delay recomended from datasheet
  digitalWrite(pingPin,LOW); 
  pinMode(pingPin,INPUT); 
  duration =pulseIn(pingPin,HIGH); 
  
  inches = microsecondsToInches(duration); // converting time into distance
  cm = microsecondsToCentimeters(duration); 

  Serial.print(inches); 
  Serial.print("in, "); 
  Serial.print(cm); 
  Serial.print("cm"); 
  Serial.println();
}

I'm sorry I'm really new at this and don't under stand much, where would the sensors code be in, and at the moment I'm just using two speeds 0v and 6v to power the to Dc motors, I can get the motors to stop at an object, and also get the servo to look around, but I can't get any information of the sensor to tell the bot where to go whether that will be left right or reverse, is there this could happen with some modification of my last code.

I simply took your code from the beginning of loop() in your first example and moved it
inside function read_Ping(). All you have to do is put it back in the beginning of loop().

The best way to develop code like this, especially when first learning how to code, is to
write small programs that do only "one" thing, like read a sensor and send it's value to the
PC using Serial,print(), or set the motor to different speeds using a for() loop. These should
be coded as separate routines. Then, combine the small routines into an integrated program.

Also, as mentioned, we need to know what motors and motor controller you're using to
figure out how to control motor speed. This is usually done using the Arduino PWM functions
or motor libraries, eg see,

Hi

I am using a l293d hbridge driver and two 3v dc motors, my Arduino is the UNO one, the not is a tank chassis which turns right or left by stopping the one of the Dc motors and making the other motor drive, I'm not very good at explaining it, but that is what I have, hope you can help and thanks for the reply x

As I mentioned last time, the way to proceed is to write routines for the sensors
and motors separately, figure out how to make them work, and then put the
routines together. Eg, for motor, stop, go, left, right, fast, slow. For Ping sensor,
display the values coming out versus distance from an object using Serial.print().
Then, combine them.

The code I cited last time uses PWM to run the motor at different speeds. All you
have to do is pick the right pins. The function analogWrite() is really a poorly-chosen
name, as what it is doing is changing the PWM duty cycle. See the first section here,

someone please help,

i am making a robot that away from obstacles. i am using two IR sensor for this instead of Ping sensor.
robot is autonomous.

Hey, i know it's a little bit late for this, but in this moment i have exactly the same problem that you have ( or had), and i'm wondering if could you let me know if were you able to solve it and how. Thank you !

hi
I am making robot using ic l293d to control 3v dc motors. I tested motors using the code now I am looking the code for obstacle avoidance I am using ultra sonic sensor. I am using arduino uno microcontroller.please send me code I shall be thankful to you.

@chaudhry have you got the sensor working and showing the distance on the serial monitor for example?

If not that's what you need to get right first. There's lots of code around for ultrasonics: check the Playground for the new ping library. You don't say what model sensor you have though.

Then you need to compare the actual distance to some minimum that you must decide. If the distance is less than that, take some action; if not, carry on.

You need to decide what the robot must do when it's close to an obstacle: just stop? Reverse a while? Turn left a bit? Or what....

Some folk mount the sensor on a servo, so when it's close to an obstacle it can see which is a better choice- go left or go right?

chaudhry:
hi
I am making robot using ic l293d to control 3v dc motors. I tested motors using the code now I am looking the code for obstacle avoidance I am using ultra sonic sensor. I am using arduino uno microcontroller.please send me code I shall be thankful to you.

Have a look maybe that will help you.

Hakani:
someone please help,

i am making a robot that away from obstacles. i am using two IR sensor for this instead of Ping sensor.
robot is autonomous.

Have a look 8)

what is obstacle avoiding robot code?

what is wrong with its?

#include <AFMotor.h>

AF_DCMotor leftmotors(2, MOTOR12_64KHZ);

AF_DCMotor rightmotors(1, MOTOR12_64KHZ);

AF_DCMotor armmotor(4, MOTOR34_64KHZ);

#define trigPin 12 // define the pins of the distance sensor

#define echoPin 13

void setup() {

leftmotors.setSpeed(255); // set the speed to full speed 255/255

rightmotors.setSpeed(255); //set the speed to full speed 255/255

armmotor.setSpeed(255); //set the speed for the arm

Serial.begin(9600); // begin serial communitication

Serial.println("Motor test!");

pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)

pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)

}

void loop() {

long duration, distance; // start the scan

digitalWrite(trigPin, LOW);

delayMicroseconds(2); // delays are required for a succesful sensor operation.

digitalWrite(trigPin, HIGH);

delayMicroseconds(10); //this delay is required as well!

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = ((duration/2) / (29.1));// convert the distance to centimeters.

if (distance < 10) /*if there's obstacle 10 centimers ahead, do the following: */ {

Serial.println ("Close Obstacle detected!" );

Serial.println ("Obstacle Details:");

Serial.print ("Distance From Robot is " );

Serial.print ( distance);

Serial.print ( " CM!");// print out the distance in centimeters.

Serial.println (" The obstacle is declared a threat due to close distance. ");

Serial.println (" Taking !");

STOP();

ARMF();

delay(2000);

ARMR();

BACKW();

delay(4000);

LEFT();

delay(2000);

FORW();

delay(3000);

RIGHT();

delay(2000);

FORW();

delay(8000);

STOP();

delay(4000);

ARMB();

delay(3000);

ARMR();

}

else {

Serial.println ("No obstacle detected. going forward");

delay (15);

FORW();

}

}

void FORW() {

leftmotors.run(FORWARD); // 2 left motors go in forward direction

rightmotors.run(FORWARD); // 2 right motors go in forward direction

}

void BACKW() {

leftmotors.run(BACKWARD); // 2 left motors go in backward direction

rightmotors.run(BACKWARD); // 2 right motors go in backward direction

}

void STOP() {

leftmotors.run(RELEASE); // stop 2 left motors

rightmotors.run(RELEASE); // stop 2 right motors

}

void LEFT(){

leftmotors.run(FORWARD); //2 left motors go in forward direction

rightmotors.run(BACKWARD); //2 right motors go in backward direction. This make the robot spin to the left 90 degree.

}

void RIGHT() {

leftmotors.run(BACKWARD); //the other way.

rightmotors.run(FORWARD);

}

void ARMF() {

armmotor.run(FORWARD);

}

void ARMB() {

armmotor.run(BACKWARD);

}

void ARMR() {

armmotor.run(RELEASE);

}

#include <Ultrasonic.h>
#include <Servo.h>

Ultrasonic ultrasonic(12,13);

const int RForward = 0;
const int RBackward = 180;
const int LForward = 180;
const int LBackward = 0;
const int RNeutral = 91;
const int LNeutral = 92; //constants for motor speed

const int TrigPin = 12;
const int EchoPin = 13; //Echo pin

const int dangerThresh = 10; //threshold for obstacles (in cm)
int leftDistance = 0;
int rightDistance = 0; //distances on either side

Servo HeadServo;
Servo LeftServo;
Servo RightServo; //declare servos

long duration; //time it takes to recieve ECHO))) signal

void setup()
{
pinMode(TrigPin, OUTPUT);
pinMode(EchoPin, INPUT);
RightServo.attach(11);
LeftServo.attach(10);
HeadServo.attach(6); //attach servo to proper pins
HeadServo.write(90); //centre head servo
}

void loop()
{

int distanceFwd = (ultrasonic.Ranging(CM));

Serial.begin( 9600 );
Serial.print( ultrasonic.Ranging(CM) );
Serial.println( “cm” );
delay(500);

if (distanceFwd>dangerThresh) //if path is clear

{
LeftServo.write(LForward);
RightServo.write(RForward); //move forward
}
else //if path is blocked
{
LeftServo.write(LNeutral);
RightServo.write(RNeutral);
HeadServo.write(0);
delay(500);
rightDistance = ultrasonic.Ranging(CM); //scan to the right
delay(500);
HeadServo.write(180);
delay(700);
leftDistance = ultrasonic.Ranging(CM); //scan to the left
delay(500);
HeadServo.write(90); //return to center
delay(100);
compareDistance();
}

}

void compareDistance()
{
if (leftDistance>rightDistance) //if left is less obstructed
{
LeftServo.write(LBackward);
RightServo.write(RForward); //turn left
delay(2000);
}
else if (rightDistance>leftDistance) //if right is less obstructed
{
LeftServo.write(LForward);
RightServo.write(RBackward); //turn right
delay(2000);
}
else //if they are equally obstructed
{
LeftServo.write(LForward);
RightServo.write(RBackward); //turn 180 degrees
delay(2000);
}
}

long ping()
{
// Send out PING))) signal pulse
pinMode(TrigPin, OUTPUT);
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(5);
digitalWrite(TrigPin, LOW);

//Get duration it takes to receive echo
pinMode(TrigPin, INPUT);
duration = pulseIn(TrigPin, HIGH);

//Convert duration into distance
return duration / 29 / 2;
}

Is there a question?

Will we be seeing your code inside code tags?

What is the ping() function for? You never call it.

compareDistance() is a dumb name for a function that does a whole lot more than that.

Am making a obstical avoiding car...my whole circuit is ok.. but I am not been able to upload the codes....each time l try it doesn't compile and without compiling l can't upload the codes .. it shows that l have some data (newping)missing ...plz anybody help me with providing a valid code..

The code l used

// Arduino Obstacle Avoiding Robot
// Code adapted from http://www.educ8s.tv
// First Include the NewPing and Servo Libraries

#include <NewPing.h>http:max
#include <Servo.h>

#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE 200
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
Servo myservo;

boolean goesForward=false;
int distance = 100;
int speedSet = 0;

const int motorPin1 = 11;
const int motorPin2 = 10;
//Motor B
const int motorPin3 = 6;
const int motorPin4 = 5;

void setup() {

myservo.attach(9);
myservo.write(115);
delay(2000);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
}

void loop() {
int distanceR = 0;
int distanceL = 0;
delay(40);

if(distance<=20)
{
moveStop();
delay(100);
moveBackward();
delay(300);
moveStop();
delay(200);
distanceR = lookRight();
delay(200);
distanceL = lookLeft();
delay(200);

if(distanceR>=distanceL)
{
turnRight();
moveStop();
}else
{
turnLeft();
moveStop();
}
}else
{
moveForward();
}
distance = readPing();
}

int lookRight()
{
myservo.write(50);
delay(500);
int distance = readPing();
delay(100);
myservo.write(115);
return distance;
}

int lookLeft()
{
myservo.write(170);
delay(500);
int distance = readPing();
delay(100);
myservo.write(115);
return distance;
delay(100);
}

int readPing() {
delay(70);
int cm = sonar.ping_cm();
if(cm==0)
{
cm = 250;
}
return cm;
}

void moveStop() {
analogWrite(motorPin1, 0);
analogWrite(motorPin2, 0);
analogWrite(motorPin3, 0);
analogWrite(motorPin4, 0);
}

void moveForward() {

analogWrite(motorPin1, 180);
analogWrite(motorPin2, 0);
analogWrite(motorPin3, 180);
analogWrite(motorPin4, 0);

}

void moveBackward() {

analogWrite(motorPin1, 0);
analogWrite(motorPin2, 180);
analogWrite(motorPin3, 0);
analogWrite(motorPin4, 180);

}

void turnRight() {
analogWrite(motorPin1, 180);
analogWrite(motorPin2, 0);
analogWrite(motorPin3, 0);
analogWrite(motorPin4, 180);
delay(300);
moveForward();

}

void turnLeft() {
analogWrite(motorPin1, 0);
analogWrite(motorPin2, 180);
analogWrite(motorPin3, 180);
analogWrite(motorPin4, 0);
delay(300);
moveForward();
}

Am using Arduino nano ATmega328 ... regarding that plz provide me a code

The components am using
1------WD4 robot chassis
2-------arduino nano AT MEGA 328
3--------ultrrasonic senior
4--------Robodo Electronics L298 Motor Driver Module
5-----BB-801 400 Tie Point Solderless Breadboard Circuit Experiment Accessory
6-----BRC 18650 6800mah battery