Challenge

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

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

ANS:

CODE:

int Index_in = 0;
int Index_cms = 0;
float Sum_in = 0.0;
float Sum_cms = 0.0;
float Readings_in[5];
float Readings_cms[5];
float Averaged_in = 0.0;
float Averaged_cms = 0.0;
void setup()
{
Serial.begin(9600); //Initializing UART communication
}
void loop()
{
long duration, inches, cm; //Declaration of variables to store ping duration and distance of object
pinMode(7, OUTPUT); //Using pin 7 to send a pulse
digitalWrite(7, LOW);
delayMicroseconds(2);
digitalWrite(7, HIGH);
delayMicroseconds(5);
digitalWrite(7, LOW);
pinMode(7, INPUT); //Using the same pin as input to read echo
duration = pulseIn(7, HIGH); //Reading the ping duration
inches = microsecondsToInches(duration); //Converting duration into distance in inches
cm = microsecondsToCentimeters(duration); //Converting duration into distance in cms
Serial.println();
Serial.println("Raw Data: ");
Serial.print(inches); //Printing the distance in inches and cms
Serial.print(" in ");
Serial.print(cm);
Serial.println(" cms ");
Serial.println();
delay(1000);
/*Implementation of moving average filter for smoothening the inches data*/
Sum_in -= Readings_in[Index_in];
Readings_in[Index_in] = inches;
Sum_in = Sum_in + inches;
Index_in = (Index_in+1)%5;
Averaged_in = Sum_in/5;
delay(25);
/*Implementation of moving average filter for smoothening the cms data*/
Sum_cms -= Readings_cms[Index_cms];
Readings_cms[Index_cms] = cm;
Sum_cms = Sum_cms + cm;
Index_cms = (Index_cms+1)%5;
Averaged_cms = Sum_cms/5;
delay(25);
Serial.println("Smoothened Data: "); //Printing the smoothened data
Serial.print(Averaged_in);
Serial.print(" in ");
Serial.print(Averaged_cms);
Serial.print(" cms");
Serial.println();
delay(1000);
}
long microsecondsToInches(long microseconds) //Function for calculating the distance in inches
{
return microseconds / 73.746 / 2;
}
long microsecondsToCentimeters(long microseconds) //Function for calculating the distance in cms
{
return microseconds / 29 / 2;
}
OUTPUT:
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.