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);
}
#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?
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