Challenge

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

#define pingPin 7

// Variables for moving average filter

const int numReadings = 10; // Number of readings to average

int readings[numReadings]; // The readings from the Ping sensor

int readIndex = 0; // The index of the current reading

int total = 0; // The total of the readings

int average = 0; // The average of the readings

void setup() {

// Initialize serial communication

Serial.begin(9600);

// Initialize all the readings to 0

for (int i = 0; i < numReadings; i++) {

readings[i] = 0;

}

}

void loop() {

// Get the current distance reading

long duration, cm;

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

cm = microsecondsToCentimeters(duration);

// Update the moving average

total = total - readings[readIndex];

readings[readIndex] = cm;

total = total + readings[readIndex];

readIndex = readIndex + 1;

if (readIndex >= numReadings) {

readIndex = 0;

}

average = total / numReadings;

// Print the smoothed distance

Serial.print("Distance: ");

Serial.print(average);

Serial.println(" cm");

delay(100);

}

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.

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.