How to store distance data in array and calculate average of data from ultrasonic sensor

I have tried this below code to get data from ultrasonic sensor of a particular object distance and store it in a array to calculate it average distance.

 #define trigPin 5
#define echoPin 2


long duration=0;
long distance=0;
long RightSensor=0;
int timeR=0;
int sum=0;
int my_array[5];

 void setup()  
 {  
  Serial.begin(9600);  

  Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

 }

  void loop()  
 {  
 

  




 
  for (int i=0;i<5;i++){ 
   RightSensor = dist();
   
   if(RightSensor<15){
    for (int i=0;i<5;i++){ 
    my_array[i] = RightSensor; 
     Serial.print("Distance From the Hazard Point = ");
  
Serial.println(RightSensor);
delay(500);
  }
  }
 

 
 }}







long dist(){                 
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration/58.2;
  

  return(distance);
}

And? Did you get results? Were they correct? Were the results what you actually measured?

the data i was getting it prints 5 times but i want to store of 5 data in array.

Try:

#define trigPin 5
#define echoPin 2

long duration = 0;
long distance = 0;
long RightSensor = 0;
int timeR = 0;
int sum = 0;
int my_array[5];

void setup()
{
  Serial.begin(9600);

  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop()
{
  // acquire and store the readings
  for (int i = 0; i < 5; i++) {
    RightSensor = dist();
    my_array[i] = RightSensor;
    delay(500);
  }

  // print the readings
  for (int i = 0; i < 5; i++) {
    Serial.print("Distance From the Hazard Point = ");
    Serial.println(my_array[i]);
  }
}

long dist() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration / 58.2;

  return (distance);
}

I would check to see what range of distances can be returned by the ultrasonic sensor. Your dist() function returns a LONG but your my_array is only an INT.

What is the significance of the reading being less than 15?

You seem to be looping 25 times - why?

Rolling average:

Moving average filter - Using Arduino / Sensors - Arduino Forum

i want to store data for finite range . then storing it in a array suppose 5 data has store in this finite location then i will sum this and give a average distance of that 5 data.
By the way thank you so much

Is the data correct? If not fix that first.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.