Challenge

Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter

1)

#define pingpin 5// define the trigger pin
int reading[5]={0};//array declaration initialized with zero
int i;//variable for index
int sum=0;//variable for storing sum
int j;//variable for index
int value;//for storing the digital value
float average=0;//for storing the average value
float distance=0;//for storing the distance value in "inches"
void push(int val)//function for pushing the newly coming data to array
{//like the queue data structure entry in one end and deletion in other
for(i=1;i<=5;i++)
{
reading[i-1]=reading[i];
}
reading[i]=val;
}
int avg()//function for getting the sum of the array of readings
{

for(j=0;j<5;j++)
{
sum=sum+reading[j];

}
return sum;//

}
void setup()
{
Serial.begin(9600);//for beginning the serial monitor

}

void loop()
{
pinMode(pingpin,OUTPUT);
digitalWrite(pingpin,LOW);//making low pulse to high pulse
delay(2);
digitalWrite(pingpin,HIGH);
delay(10);
digitalWrite(pingpin,LOW);
pinMode(pingpin,INPUT);
value=pulseIn(pingpin,HIGH);//picking the digital value from the sensor
push(value);//pushing that digital value to the array
average=avg();//finding the average of the five values in the array
distance=average/74/2;//finding the distance
Serial.print(distance);//displaying in the serial monitor
Serial.print("inches");
Serial.println(" ");



}

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.