Skip to main content
3 of 4
Rollback to Revision 1
Nick Gammon
  • 38.9k
  • 13
  • 70
  • 127

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 <Servo.h>

// 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 <= 15 && distance >=2) {

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

for(int j=90;j>=0;j--){

myServo1.write(j);

delay(30);}

for(int j=0;j<=180;j++){

myServo1.write(j);

int i=0;

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

  for (i=0;i=180;i++){           <--------------------------------------
 
   if (dist[i]>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>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;

}