Saturday 15 December 2018

Object Avoiding Car Code :-


#include<Servo.h> 

const int trig = 7;
const int echo=8;
const int dangerThresh = 10;
int leftDistance, rightDistance;
Servo panMotor;
long duration;
void setup()
{
  pinMode(trig,OUTPUT);
  pinMode(echo,INPUT);
  panMotor.attach(6);
  panMotor.write(90);
}

void loop()
{
  int distanceFwd = ping();
  if (distanceFwd>dangerThresh)
  {
    move();
  }
  else
  {
    stop();
    panMotor.write(0);
    delay(500);
    rightDistance = ping();
    delay(500);
    panMotor.write(180);
    delay(700);
    leftDistance = ping();
    delay(500);
    panMotor.write(90);
    delay(100);
    compareDistance();
  }
}
 
void compareDistance()
{
  if (leftDistance>rightDistance)
  {
    left();
  }
  else if (rightDistance>leftDistance)
  {
    right();
  }
   else
  {
    back();
  }
}

long ping()
{
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(5);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  return duration / 29 / 2;
}
void stop(){
    digitalWrite(12,LOW);
    digitalWrite(13,LOW);
    digitalWrite(10,LOW);
    digitalWrite(11,LOW);
}
void left(){
    digitalWrite(12,LOW);
    digitalWrite(13,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(11,LOW);
    delay(500);
}
void right(){
    digitalWrite(12,HIGH);
    digitalWrite(13,LOW);
    digitalWrite(10,LOW);
    digitalWrite(11,HIGH);
}
void back(){
    digitalWrite(12,HIGH);
    digitalWrite(13,LOW);
    digitalWrite(10,LOW);

    digitalWrite(11,HIGH);
}
void move(){
    digitalWrite(10,HIGH);

    digitalWrite(11,LOW);
    digitalWrite(12,HIGH);

    digitalWrite(13,LOW);
}

                                                            -Piyush Yadav

No comments:

Post a Comment