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 windowSize = 5; // Size of the moving average window
long readings[windowSize]; // Array to store sensor readings
int index = 0; // Index to keep track of the current position in the array
long total = 0; // Variable to store the sum of the readings

void setup() {
  Serial.begin(9600);
}

void loop() {
  long duration, inches, cm;

  // Send ping
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // Receive pong
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // Store the new reading in the array
  total -= readings[index]; // Subtract the oldest reading from the total
  readings[index] = duration; // Store the new reading
  total += duration; // Add the new reading to the total

  // Increment index and wrap around if necessary
  index++;
  if (index >= windowSize) {
    index = 0;
  }

  // Calculate the moving average
  long movingAverage = total / windowSize;

  // Convert the time into distances
  inches = microsecondsToInches(movingAverage);
  cm = microsecondsToCentimeters(movingAverage);

  // Print distances
  Serial.print("Moving Average - Inches: ");
  Serial.print(inches);
  Serial.print(" in, Centimeters: ");
  Serial.print(cm);
  Serial.println(" cm");

  delay(100);
}

long microsecondsToInches(long microseconds) {
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  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.