Challenge

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

ANSWER:

int inches = 0;

int cm = 0;
int temp=0;
int avg=0;

long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}

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

void loop()
{
cm=0;
inches=0;
temp=0;
// measure the ping time in cm
cm = 0.01723 * readUltrasonicDistance(7, 7);//(1/2*29) because sound travels at a
//speed of 343m/s,2 states that 2times the signal travels
// convert to inches by dividing by 2.54
inches = (cm / 2.54);
for(int i=0;i<10;i++)
{
temp=temp+inches;//taking the inch values
avg=temp/10;//averaging the inch values

}
Serial.println("THE DISTANCE:");
Serial.print(inches);
Serial.println("in");
Serial.println("THE DISTANCE AFTER SMOOTHENING FILTER:");
Serial.print(avg);
Serial.println("in");
delay(500); // Wait for 500 millisecond(s)
}

CIRCUIT DIAGRAM:

OUTPUT:

THE DISTANCE: 60in

THE DISTANCE AFTER SMOOTHENING FILTER: 60in

THE DISTANCE: 60in

THE DISTANCE AFTER SMOOTHENING FILTER: 60in

THE DISTANCE: 60in

THE DISTANCE AFTER SMOOTHENING FILTER: 60in

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.