Hi, I'm student and I'm new with Arduino. Right now I'm doing a robot that with a distance detector and two servos, can see if there's enough distance and if there is not it can turn and go to another side. I want to improve this robot and I want it to look at both sides and then go to the side where is modre distance avaiable. I don't really know how to do it so it would be great if someone could help me. My code is this:
#include <Servo.h>
Servo ServoRight;
Servo ServoLeft;
int trigPin = 9;
int echoPin = 10;
long duration, distance;
void setup() {
ServoRight.attach(2);
ServoLeft.attach(3);
delay(random(500,2000));
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
duration = pulseIn(echoPin, HIGH);
distance = duration / 58.2;
delay(10);
if (distance > 30)
{
ServoRight.write(180);
ServoLeft.write(0);
ServoLeft.write(90);
delay(500);
ServoRight.write(0);
ServoLeft.write(180);
delay(600);
ServoRight.write(90);
ServoLeft.write(90);
delay(300);
ServoRight.write(180);
ServoLeft.write(180);
delay(1000);
}
if (distance < 18)
{
ServoRight.write(90);
ServoLeft.write(90);
ServoLeft.write(90);
delay(500);
ServoRight.write(0);
ServoLeft.write(180);
delay(600),
ServoRight.write(90);
ServoLeft.write(90);
delay(300);
ServoRight.write(180);
ServoLeft.write(180);
delay(500);
}
}
Thank you!