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.
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);
}
}