Challenge

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

const int pingPin = 7;

const int numReadings = 5; // Number of readings for the moving average

void setup() {

Serial.begin(9600);

}

void loop() {

long duration, inches, cm;

// Array to store distance readings for the moving average

long readings[numReadings];

long total = 0;

int index = 0;

// Initially, the code sets the pingpin to a LOW state. After setting the pin to LOW, there's a very short delay of 2 milliseconds. The HIGH state is maintained for a very short duration (5 milliseconds) to create the pulse.

pinMode(pingPin, OUTPUT);

digitalWrite(pingPin, LOW);

delayMicroseconds(2);

digitalWrite(pingPin, HIGH);

delayMicroseconds(5);

digitalWrite(pingPin, LOW);

pinMode(pingPin, INPUT);

duration = pulseIn(pingPin, HIGH);

// Convert the time into a distance

inches = microsecondsToInches(duration);

cm = microsecondsToCentimeters(duration);

/// code will provide a smoother representation of the distance measurements over time by calculating the moving average.

// Add the current reading to the array and update the total

total = total - readings[index];

readings[index] = cm;

total = total + cm;

index = (index + 1) % numReadings;

// Calculate the moving average

long movingAverage = total / numReadings;

Serial.print("Distance: ");

Serial.print(cm);

Serial.print("cm, ");

Serial.print("Moving Average: ");

Serial.print(movingAverage);

Serial.println("cm");

delay(100);

}

long microsecondsToInches(long microseconds) {

// According to Parallax's datasheet for the PING))), there are 73.746

// microseconds per inch (i.e. sound travels at 1130 feet per second).

// This gives the distance traveled by the ping, outbound and return,

// so we divide by 2 to get the distance of the obstacle.

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 traveled.

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.