Project 2 - Measuring the distance of an object using ultrasonic sensor and also smoothen the sensor data using moving average filter
Project: In this project the implementation of code for “Measuring distance of an object using ultrasonic distance sensor (28015 Ping) and also smoothen the sensor data using moving average filter”.
Code:
#define trigPin 9 // Define the pin9 for the triggering_pin of ultrasonic sensor
#define echoPin 10 // Define the pin9 for the triggering_pin of ultrasonic sensor
#define numSamples 10 // Define the number of samples for the moving average filter
int samples[numSamples]; // Define an array to hold the samples
int currentSample = 0; // Define a variable to hold the index of the current sample
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(trigPin, OUTPUT); // Set the trigger pin as an output
pinMode(echoPin, INPUT); // Set the echo pin as an input
}
void loop() {
// Send a pulse to the ultrasonic sensor to trigger a measurement
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse and calculate the distance in centimeters
float duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2;
// Add the current sample to the array and increment the index
samples[currentSample] = distance;
currentSample++;
// Wrap around the index if it exceeds the number of samples
if (currentSample >= numSamples) {
currentSample = 0;
}
// Calculate the moving average of the samples
float sum = 0;
for (int i = 0; i < numSamples; i++) {
sum += samples[i];
}
float averageDistance = sum / numSamples;
// Print the raw and smoothed distances
Serial.print("Raw distance: ");
Serial.print(distance);
Serial.print(" cm, ");
Serial.print("Smoothed distance: ");
Serial.print(averageDistance);
Serial.println(" cm");
// Wait for a short delay before taking the next measurement
delay(50);
}



