Challenge

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

Overview of the Project:

In this project the implementation of code for “Measuring distance of an object using ultrasonic distance sensor (28015 Ping) and also smoothen the sensor data using moving average filter”.

General Overview of How an Ultrasonic Distance Sensor Works

An ultrasonic distance sensor, such as the 28015, uses sound waves to measure the distance to an object. Here's a step-by-step explanation of how it works:

  1. Emission of Sound Waves:

    • The sensor has a transmitter that emits a burst of ultrasonic sound waves at a specific frequency (typically around 40 kHz, which is inaudible to humans).
  2. Reflection of Sound Waves:

    • When these sound waves hit an object, they bounce back (echo) towards the sensor.
  3. Reception of Echo:

    • The sensor also has a receiver that listens for the reflected sound waves.
  4. Time Measurement:

    • The sensor measures the time it takes for the sound waves to travel from the sensor to the object and back. This time interval is crucial for calculating the distance.
  5. Distance Calculation:

    • Using the speed of sound (approximately 343 meters per second at room temperature), the sensor calculates the distance to the object with the formula: Distance=Time×Speed of Sound2\text{Distance} = \frac{\text{Time} \times \text{Speed of Sound}}{2}Distance=2Time×Speed of Sound​


Code:

int inches = 0;

int cm = 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); // no. of bits transmitting per second

}


void loop()

{

// measure the ping time in cm

cm = 0.01723 * readUltrasonicDistance(7, 7);

// convert to inches by dividing by 2.54

inches = (cm / 2.54);

Serial.print(inches);

Serial.print("in, ");

Serial.print(cm);

Serial.println("cm");

delay(100); // Wait for 100 millisecond(s)

}




OUTPUT ATTACHED BELOW




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.