Help with code

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!

ServoRight.attach(2);
   ServoLeft.attach(2);

2 servos on the same pin ?

Please follow the advice on posting code given in posting code

In particular note the advice to Auto format code in the IDE and to use code tags when posting code here as it prevents some combinations of characters in code being interpreted as HTML commands such as italics, bold or a smiley character, all of which render the code useless

Oh yes, my mistake. It is actually in two different pins. I may have changed it when I copyed it.

Wouldn't this just be a simple logic problem?

if distanceLeft < distanceRight
 then turn right
else
 then turn left

compare the distances and turn in the direction of the greatest distance, right?

Randy

Basics first. Are your "servos" real servos or are they continuous rotation servos? So not really servos any more just geared motors that drive the robot? And why do you write(0) and then immediately after write(90) to one of them?

If you want distances on both sides you either need another 2 ultrasonic sensors or you need your sensor mounted on a servo to swing it from side to side. Your choice, there are many examples around of both versions.

Steve

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.