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

#define trigPin 2
#define echoPin 3
const int numReadings = 10; // Number of readings for moving average filter
long readings[numReadings]; // Array to hold distance readings
int readIndex = 0; // Index of the current reading
long total = 0; // Sum of the readings
long average = 0; // Average of the readings
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(trigPin, OUTPUT); // Set the trigger pin as output
pinMode(echoPin, INPUT); // Set the echo pin as input
// Initialize all readings to 0
for (int i = 0; i < numReadings; i++) {
readings[i] = 0;
}
}
void loop() {
// Get a new distance reading
long duration, inches;
// Send a 10us pulse to trigger the sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin for the duration of the high pulse
duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance
inches = microsecondsToInches(duration);
// Update the moving average filter
total = total - readings[readIndex]; // Subtract the oldest reading
readings[readIndex] = inches; // Add the new reading
total = total + readings[readIndex]; // Add the new reading to the total
readIndex = readIndex + 1; // Advance to the next position in the array
// Wrap around if necessary
if (readIndex >= numReadings) {
readIndex = 0;
}
// Calculate the average
average = total / numReadings;
// Print the average distance
Serial.print("Average distance (inches): ");
Serial.println(average);
delay(100); // Delay before the next reading
}
long microsecondsToInches(long microseconds) {
// Convert the time into a distance in inches
return microseconds / 74 / 2;
}
output:
