Pages: [1]   Go Down
Author Topic: My Obstacle Avoiding Robot Code needs some Improvement!  (Read 471 times)
0 Members and 1 Guest are viewing this topic.
India
Offline Offline
Newbie
*
Karma: 0
Posts: 17
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:

#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);
 }
     
Logged

Global Moderator
Boston area, metrowest
Offline Offline
Brattain Member
*****
Karma: 534
Posts: 26969
Author of "Arduino for Teens". Available for Design & Build services. Now with Unlimited Eagle board sizes!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Please post a schematic.
What kind of 9V battery?
Logged

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.

Poole, Dorset, UK
Offline Offline
Edison Member
*
Karma: 52
Posts: 2277
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Mark
Logged

Pages: [1]   Go Up
Jump to: