Challenge

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

//Initialization

const int pingPin = 9;

void setup() {

// initialize serial communication:

Serial.begin(9600);

}

void loop() {

// establish variables for duration of the ping, and the distance result in inches and centimeters:

long duration, inches, cm;

pinMode(pingPin, OUTPUT);

digitalWrite(pingPin, LOW);

delayMicroseconds(2);

digitalWrite(pingPin, HIGH);

delayMicroseconds(5);

digitalWrite(pingPin, LOW);

pinMode(pingPin, INPUT);

duration = pulseIn(pingPin, HIGH);

// convertion of the time into a distance

//Distance measurement function

inches = microsecondsToInches(duration);

cm = microsecondsToCentimeters(duration);

Serial.print(inches);

Serial.print("inch, ");

Serial.print(cm);//printing the distance in inches

Serial.print("cms");

Serial.println();////printing the distance in cms

delay(100);//i gave delay of 0.1 second

}

long microsecondsToInches(long microseconds)

{

return microseconds / 74 / 2;

}

long microsecondsToCentimeters(long microseconds)

{

// The speed of sound is 340 m/s or 29 microseconds per centimeter.

// The ping travels out and back, so to find the distance of the object we

// take half of the distance travelled.

return microseconds / 29 / 2;

}

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.