How to store values from a sensor inside an empty array? I need to store the value of the distance in the dist array, then calculate the maximun value and print the index associated with this value:

The problem is when starting the nested for inside another for, the servomotor stops working

// Includes the Servo library
#include &lt;Servo.h&gt;

// Array y valores para funcion valor maximo

int max=0;

int angle=0;

int distance=0;

// Defines Tirg and Echo pins of the Ultrasonic Sensor

const int trigPin = 10;

const int echoPin = 11;

// Variables for the duration and the distance

long duration;

//int distance[180];

Servo myServo1; // Creates a servo object for controlling the servo motor

void setup() {

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

  pinMode(echoPin, INPUT); // Sets the echoPin as an Input

  Serial.begin(9600);

  myServo1.attach(12); // Defines on which pin is the servo motor attached
  }

void loop() {

distance = calculateDistance();
  if (distance &lt;= 15 &amp;&amp; distance &gt;=2)
  {

  // rotates the servo motor from 1 to 179 degrees and calculate the distance at each angle

  for(int j=90;j&gt;=0;j--){

  myServo1.write(j);

  delay(30);}


  for(int j=0;j&lt;=180;j++){  

  myServo1.write(j); 

  int i=0; 

  int  dist [i] = {calculateDistance()};

      for (i=0;i=180;i++){           &lt;--------------------------------------

       if (dist[i]&gt;max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);}

  }
      }

  // Repeats the previous lines from 179 to 90 degrees

for(int j=180;j&gt;90;j--){  

  myServo1.write(j);

  delay(30);

  }
}
}

// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance(){ 

  digitalWrite(trigPin, LOW); 

  delayMicroseconds(2);

  // Sets the trigPin on HIGH state for 10 micro seconds

  digitalWrite(trigPin, HIGH); 

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds

  distance= duration*0.034/2;

  return distance;

}
int i=0; 
  int  dist [i] = {
    calculateDistance()      };


I'm not sure what you are thinking here, but you obviously cannot store data into a zero-length array. You also cannot put a function call to populate an array of variable length.

You need to decide how many elements you need in the array, in advance, and allocate an array of that size.



Maybe more like this:

 int  dist [180];

  for (i=0;i&lt;180;i++){    
    dist [i] = calculateDistance ();
    if (dist[i]&gt;max){
      max=dist[i];
      angle=i;
      Serial.print(angle);
      delay(30);
    }

  }




Also, this is wrong in your code:

for (i=0;i=180;i++){  


You need to test for &lt; 180 here. Your for loop will assign 180 to i and then check to see if it is non-zero, which will always be true.