Need a bit of help with HC-SR04 sensor

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) >

image

Show us a good schematic of your proposed circuit.
Show us a good image of the wiring.
Give links to components.

That will be using the same units as you use for the speed of sound in your distance calculation.
Paul

Say what ?

sending data in float

cannot produce that sorry

A pencil and paper is all you need.

Centimetres.

What happens to the distance values when you try to follow the sensor by placing a flat sheet of something perpendicular to the imaginary line of sight of he SR04, say 30 cm away?

The distance sound travels in 29.41 microseconds: 1 cm.

Something doesn't seem right since there is no way the distance is over 32 meters.

You should use 'unsigned long duration;' since that is the type that pulseIn() returns.

Multiply microseconds (duration) by the speed of sound in cm per microsecond (0.034) and then divide by 2 to account for round-trip time.

Most people use integers:

unsigned long duration = pulseIn(EchoPin, HIGH, 30000);
unsigned distance = duration / 58; // Round-trip microseconds per cm