Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
1.4 kB
1
Indexable
Never
#include <AFMotor.h>
#include <Servo.h>

AF_DCMotor motor2(2);
AF_DCMotor motor1(1);

// defines variables
long duration;
int distance;

void setup()
{
 Serial.begin(9600);
  motor1.setSpeed(100);
  motor2.setSpeed(100);

  pinMode(A0,OUTPUT); //TRIG
  pinMode(A1,INPUT); // ECHO
  
  motor1.run(RELEASE);
  motor2.run(RELEASE);
}

void go()
{
  motor1.run(BACKWARD);
  motor2.run(FORWARD);
  delay(300);
  stop();
}

void stop()
{
  motor1.run(RELEASE);
  motor2.run(RELEASE);
}


void left()
{
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  delay(300);
  stop();
}

void right()
{
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  delay(300);
  stop();
}

void loop()
{
  int dissum=0;
  for(int i=0;i<100;i++)
  {
  digitalWrite(A0,LOW);
  delayMicroseconds(2);
  digitalWrite(A0,HIGH);
  delayMicroseconds(10);
  digitalWrite(A0,LOW);
  duration = pulseIn(A1,HIGH);
  distance = duration * 0.034/2;
  dissum=dissum+distance;
  }
  dissum=dissum/100;
  Serial.print(dissum);

  if(Serial.available() > 0)
  {
    String data = Serial.readStringUntil('\n');
    if(data.compareTo("GO")==0)
      go();
      else
        if(data.compareTo("STOP")==0)
        stop();
        else
          if(data.compareTo("LEFT")==0)
          left();
          else
            if(data.compareTo("RIGHT")==0)
            right();
    
  }
  
  
}