Challenge

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

long duration, cm, inches;//declaring variables
long sum=0; // initiallly we're assigning as zero
long avg;//declaring variables
int i;//declaring variables

void setup()

{
Serial.begin (9600); //baudrate

}
long read(int trigPin,int echoPin)//called fuction

{pinMode(trigPin, OUTPUT);//declaring output pin

digitalWrite(trigPin, LOW);//passing pulse to trigger the trigger pin
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);//passing pulse to trigger the trigger pin
delayMicroseconds(10);
digitalWrite(trigPin, LOW);//passing pulse to trigger the trigger pin
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);//actually wait for the ECHO pin go HIGH, then start measuring the pulse length until it goes LOW again.

return duration;
}
void loop()

{
long sense=read(7,7);//calling fuction
cm = (sense/2) / 29.1;
inches = (duration/2) / 74;
for (i=0; i<5; i++)//to get average of inches
{
sum=sum+inches;
avg = sum/5;
}
Serial.print(avg);//to print avarage value on serial monitor
Serial.print("Avg, ");
Serial.print(cm);//to print cm value on serial monitor
Serial.print("cm");
Serial.println();
Serial.print(inches);//to print inches value on serial monitor
Serial.print("in");
Serial.println();
delay(250);
}

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.