Go Down

Topic: My Obstacle Avoiding Robot Code needs some Improvement! (Read 496 times) previous topic - next topic

AyushChand

Here is my code i tried on my obstacle avoiding robot. It's pretty basic. I used two 12V geared motors, HCSR04 as distance sensor, Micro 9G servo to rotate, UNO. I used 2 NPN transistors to isolate the motors from arduino so that i can power it using 9V battery. A HIGH signal to the base of transistor makes the motor ON. Given below is my code. Please provide your valuable suggestions.

Code: [Select]


#define trigPin 8
#define echoPin 12
#include <Servo.h>



Servo myservo;
void setup(){
  myservo.attach(9);
  pinMode(3,OUTPUT);
  pinMode(13,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7, OUTPUT);
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void servos()
{
                                   
    myservo.write(0);             
    delay(1000);
if(ping()>40){
 
   digitalWrite(3,LOW);
   digitalWrite(6,LOW);
   
   digitalWrite(6,HIGH);
   delay(2000);
   
}
else
{
  digitalWrite(3,LOW);
   digitalWrite(6,LOW);
   
   digitalWrite(3,HIGH);
   delay(2000);
   
}
   
   
   
 
    myservo.write(90);
    delay(5000);
   
}

int ping(){
 
 
  long duration, distance;
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
   
  }

  return(distance);
}


void loop(){
 

  Serial.print(ping());
    Serial.println("cm");

if( ping()<40){

   digitalWrite(13,HIGH);
   digitalWrite(3,LOW);
   digitalWrite(6,LOW);
   
   delay(1000);
   servos();
}

else{
   
   digitalWrite(13,LOW);
   digitalWrite(3,HIGH);
   digitalWrite(6,HIGH);
}
     

CrossRoads

Please post a schematic.
What kind of 9V battery?
Designing & building electrical circuits for over 25 years. Check out the ATMega1284P based Bobuino and other '328P & '1284P creations & offerings at  www.crossroadsfencing.com/BobuinoRev17.
Arduino for Teens available at Amazon.com.

holmes4

Get rid of the delays. Look at the blink without delay example.

Mark

Go Up