I have the following code for running 2 servos as pan/tilt and a single HC-SR04 sensor. The setup is shown in the image.
#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 // attach pin D3 Arduino to pin Trig of HC-SR04
#include <Servo.h>
// defines variables
float duration; // variable for the duration of sound wave travel
float distance; // variable for the distance measurement
Servo servo1;
Servo servo2;
// sweet spot for scanning is 30-150 deg
int da= 30;
void setup()
{
servo1.attach(9); // top servo, move after every rotation.
servo2.attach(10); // bottom servo, rotates everytime.
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(115200);
servo1.write(da);
servo2.write(30);
}
void loop()
{
servo1.write(da);
if(da>110)
{
Serial.println("END");
exit(0);
}
for ( int pos = 30; pos <= 150; pos=pos+5)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(30);
digitalWrite(trigPin, LOW);
duration = (float)pulseIn(echoPin, HIGH);
distance = duration * 0.034f / 2.0f;
servo2.write(pos);
Serial.print(distance);
Serial.print(" ");
Serial.print(pos);
Serial.print(" ");
Serial.print(da);
Serial.print("\n");
delay(1000);
}
for(int pos = 110 ; pos >= 30; --pos)
{
digitalWrite(echoPin, LOW);
servo2.write(pos);
delay(10);
}
da=da+5;
}
I have a question - what will be the distance unit here?
An issue here is that it sends this random set of values
the data is in the format < distance, (x rotation angle), (y rotation angle) >