Challenge

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

The Below Screen Shot shows the OUTPUT from a ultrasonic ping sensor (28015 ping) which is smoothened and printed in the Serial Monitor.

//CODE

#define PING_PIN 9 

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

long readings[numReadings]; // Array to store the readings

int index = 0; // Index of the current reading

long total = 0; // Total of all readings

void setup() {

  Serial.begin(9600);

  // Initialize the readings array

  for (int i = 0; i < numReadings>

    readings[i] = 0;

  }

}

void loop() {

  //starting Triggering the Ping sensor

  pinMode(PING_PIN, OUTPUT);

  digitalWrite(PING_PIN, LOW);

  delayMicroseconds(2);

  digitalWrite(PING_PIN, HIGH);

  delayMicroseconds(5);

  digitalWrite(PING_PIN, LOW);

  //This piece of code is to read the Ping sensor's response

  pinMode(PING_PIN, INPUT);

  long duration = pulseIn(PING_PIN, HIGH);

  //this code is to convert duration to distance in centimeters.

  long distance = duration / 29 / 2;

  //Update the moving average

  total = total - readings[index];

  readings[index] = distance;

  total = total + distance;

  index = (index + 1) % numReadings;

  // Calculate the average distance

  long averageDistance = total / numReadings;

  Serial.print("Average Distance: ");

  Serial.print(averageDistance);

  Serial.println(" cm");

  delay(100); 

}

_____________________________________________________________________________________

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.