X1 servo controlled by 2 ultrasonic sensors

Hello ,
I have written some code to control a servo motor using the input of x2 ultrasonic sensors, I am using an arduino uno and x2 HCSR04 sensors..
im at a stop as the sensors are simply returning 0, but the code compiles.
Im just wondering if someone could help me find the solution to the problem of why I am getting 0-0 back from the x2 sensors?
And also, if someone could help me put together the next few lines of code - I want the motor to turn one direction if the first sensor is triggered, and turn the opposite direction if the second sensor is triggered.
I appreciate all of your assistance and guidance.
Thank you very much for your time and help.
:slight_smile:

Here is my code:

#include <Servo.h>

#define trigPin1 3
#define echoPin1 2
#define trigPin2 4
#define echoPin2 5

Servo servo;
long duration, distance1, distance2, RightSensor,LeftSensor;

void setup()
{
Serial.begin (9600);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
}

void loop() {
servo.attach(8);
SonarSensor(trigPin1, echoPin1);
RightSensor = distance1;
SonarSensor(trigPin2, echoPin2);
LeftSensor = distance2;


Serial.print(LeftSensor);
Serial.print(" - ");
Serial.println(RightSensor);
}

void SonarSensor(int trigPin,int echoPin)
{
digitalWrite(trigPin1, LOW);
delayMicroseconds(2);
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
duration = pulseIn(echoPin1, HIGH);
distance1 = (duration/2) / 29.1;

digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
duration = pulseIn(echoPin2, HIGH);
distance2 = (duration/2) / 29.1;


if (distance1 < distance2 ) {


servo.writeMicroseconds(1900);

delay(1500);
  }


else {

servo.writeMicroseconds(1500);

}


if (distance1 > distance2 ) {


servo.writeMicroseconds(1100);

delay(1500);
  }


else {

servo.writeMicroseconds(1500);


}
}

A guess.... Comment out the servo and see if that makes any difference.

If the sensors are wired correctly, a return value of zero means that no echo was detected.

Hi,
Start by writing code for JUST ONE ultrasonic sensor, use the NewPing library to make things easier and get the distance to appear on the IDE monitor.

Can you please post a circuit diagram of your project?
Include power supplies, component labels and pin names.

Thanks.. Tom.. :smiley: :+1: :australia: :coffee:

Double check the wiring on your sensors. How is your servo powered?

Also, you only need to attach the servo to the pin one time. Move this line to setup():

servo.attach(8);

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