Challenge

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

const int numReadings = 10; // number of readings to take for moving average filter
int readings[numReadings]; // array to store readings for moving average filter
int index = 0; // current index in the readings array
int total = 0; // total of readings for moving average filter
int average = 0; // average of readings for moving average filter

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);
for (int i = 0; i < numReadings; i++) {
readings[i] = 0;
}
}

void loop()
{
// measure the ping time in cm
int cm = 0.01723 * readUltrasonicDistance(7, 7);

// add current reading to total and subtract the oldest reading for moving average filter
total = total - readings[index] + cm;
// store current reading in the readings array
readings[index] = cm;
// move to the next index in the readings array
index = (index + 1) % numReadings;
// calculate the average of the readings for moving average filter
average = total / numReadings;

// convert to inches by dividing by 2.54
int inches = cm / 2.54;

Serial.print("Distance: ");
Serial.print(inches);
Serial.print(" in, ");
Serial.print(cm);
Serial.print(" cm, ");
Serial.print("Moving average: ");
Serial.println(average);

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

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.