#include <NewPing.h>
int Total;
const byte numReadings = 20;
byte index;
int Readings[numReadings];
int Smoothed;
#define TRIGGER_PIN 9
#define ECHO_PIN 10
#define MAX_DISTANCE 400
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
void setup(){
Serial.begin(9600);
}
void loop(){
float Ureadings = sonar.ping_cm();
Total -= Readings[index];
Readings[index] = Ureadings;
Total += Readings[index];
index += 1;
if (index >= numReadings)
{
index = 0;
}
Smoothed = Total/numReadings;
Serial.print("Distance: ");
Serial.print(Smoothed);
Serial.println("cm");
}