How to store values by ultrasonic sensor in an empty array

i have a microservo sg90 and i put over an ultrasonic sensor hc-sr04.
The micro servo takes the positions 0,30,60,90,120,150 and 180 degrees.
At each position i want to store values in empty array and then i take the biggest one

#include <Servo.h>
Servo myservo;
long duration,distance;
int echoPin = 13;
int trigPin = 12;
int pos;
int my_array[7];

void setup() {
myservo.attach(10);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myservo.write(70);
delay(2000);
Serial.begin (9600);
}

void loop() {

for (pos = 0; pos <= 180; pos += 30) {
myservo.write(pos);
Serial.println( pos);
delay(500);
}

}

void dist(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration/58.2;
Serial.print("distance ");
Serial.print(distance);
Serial.println(“cm”);
}

  for (pos = 0; pos <= 180; pos += 30) {
    myservo.write(pos);
    Serial.println( pos);
    delay(500);                   
  }

How many times does this loop iterate?
Isn’t that the same as the number of elements in the array?
So, wouldn’t this be the place to store the data in the array?
Wouldn’t

   dist();
   my_array[pos/30] = distance;

do that?

Now, having said that, there is NO reason for duration or distance to be global. dist() should return a value.

And, my_array is a stupid name for an array. It is NOT your array. It is the Arduino’s array. distances would may a much better name.

Finally, if distance is a long, int is the WRONG type of the array to hold a collection of distance values.

in each position of servo 0,30,60,90,150 and 180 degrees i want one value by the ultrasonic sensor, so the array must have 7 elements ( integer).
How to store those values in an empty array?

neofytos:
in each position of servo 0,30,60,90,150 and 180 degrees i want one value by the ultrasonic sensor, so the array must have 7 elements ( integer).
How to store those values in an empty array?

Just exactly like I showed in reply #1.

You should modify the dist() function to return the distance like this:

long dist(){                 
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration/58.2;
  Serial.print("distance ");
  Serial.print(distance);
  Serial.println("cm");

  return(distance);
}

You can easily store each reading in the existing loop:

  for (int i=0,pos = 0; pos <= 180; i++,pos += 30) {
    myservo.write(pos);
    Serial.println( pos);
    delay(500); 
    my_array[i] = dist(); 
  }

Make sure you change the type of my_array to long, since that is how you have the distance defined.