Go Down

Topic: Ping HC SR04 sensor mounted on servo (Read 74 times) previous topic - next topic

rosscopicotrain

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?

groundFungus

#1
Oct 21, 2018, 03:01 am Last Edit: Oct 21, 2018, 03:52 am by groundFungus
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:
Code: [Select]
#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()
{
   Serial.begin(115200);
   servo.write(90);
   servo.attach(servoPin);
   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("   ");
         delay(1000);
         digitalWrite(triggerPin, LOW);
         delayMicroseconds(2);
         digitalWrite(triggerPin, HIGH);
         delayMicroseconds(10);
         digitalWrite(triggerPin, LOW);
         duration = pulseIn(echoPin, HIGH);
         distance = duration * 0.034 / 2;
         distanceArray[n] = distance;
         Serial.println(distanceArray[n]);
      }
      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(maxDistance);
      Serial.print("  At  ");
      Serial.print(maxAngle);
      Serial.println(" degrees");
   }
}

Go Up