#include <NewPing.h>
// Variable initialization
int total = 0; // Sum of all readings
const byte numReadings = 5; // Number of readings to average
byte index = 0; // Current index of the readings array
int readings[numReadings] = {0}; // Array to store distance reading // Variable to store the smoothed average distance
// Pin assignments for the ultrasonic sensor
#define TRIGGER_PIN 9
#define ECHO_PIN 8
#define MAX_DISTANCE 400 // Maximum distance (in cm) to measure
// Create a NewPing object with the defined pins and max distance
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup() {
Serial.begin(9600); // Start the serial communication at 9600 baud rate
}
void loop() {
// Output the smoothed distance to the serial monitor
Serial.print("Distance: ");
Serial.print(smoothedV());
Serial.println(" cm");
}
float smoothedV(){
// Measure the distance using ultrasonic sensor (in cm)
float uReadings = sonar.ping_cm();
float smoothed;
// Remove the oldest reading from total
total -= readings[index];
// Store the new reading and add it to the total
readings[index] = uReadings;
total += readings[index];
// Move to the next index in the readings array
index += 1;
// Reset index if it reaches the maximum number of readings
if (index >= numReadings) {
index = 0;
}
// Calculate the smoothed average distance
smoothed = total / numReadings;
return smoothed;
}