Ping HC SR04 sensor mounted on servo

Hi, I am working on a robot upon which I plan to use some HC SR04 ultrasonic sensors. I was thinking of mounting one of those sensors on a servo and have it sweep back and forth reporting the closest object in terms of angle and distance.

I'm not really sure how I would approach this, does anyone have any suggestions or advice on how to go about this?

Declare an array to hold the distances. Make the array size big enough to hold the number of distances that you will acquire during one sweep. Use a for loop to iterate through the angles. For each angle (use the for index and a multiplier to set the angle), take a distance and enter the distance into the array using the for index to specify the position in the array. When done with the sweep, use another for loop to iterate through the distances array to find the max distance, The for index of the max distance will give you the angle of the max distance (times the multiplier).

Example code:

#include <Servo.h>

Servo servo;

const byte triggerPin = 4;
const byte echoPin = 5;
const byte servoPin = 7;

long duration;
int distance;
int distanceArray[7];
byte angle = 30;
int maxDistance;
int maxAngle;

void setup()
   pinMode(triggerPin, OUTPUT);

void loop()
   static unsigned long timer = 0;
   unsigned long interval = 8000;
   if (millis() - timer >= interval)
      timer = millis();
      for (int n = 0; n < 7; n++)
         servo.write(n * angle);
         Serial.print(angle * n);
         Serial.print("   ");
         digitalWrite(triggerPin, LOW);
         digitalWrite(triggerPin, HIGH);
         digitalWrite(triggerPin, LOW);
         duration = pulseIn(echoPin, HIGH);
         distance = duration * 0.034 / 2;
         distanceArray[n] = distance;
      maxDistance = 0;
      maxAngle = 0;
      for (int n = 0; n < 7; n++)
         if (distanceArray[n] > maxDistance)
            maxDistance = distanceArray[n];
            maxAngle = n * 30;
      Serial.print("Max distance = ");
      Serial.print("  At  ");
      Serial.println(" degrees");