I have revised this and got it working in a bit different way, figured I would share it in case anyone comes across this in the future.
int distances[] = {0,0,0,0,0,0,0,0,0,0};
int ez1Pin = 2;
int AverageDistance = 0;
int MinimumDistance = 0;
int SonarSamps = 9;
int i=0;
void setup() {
pinMode(ez1Pin,INPUT);
beginSerial(28800);
}
// find the position of the smallest number in an array
int MinVal (int array[], int arrayVals){
int result=0;
int i = 0;
int tempval = array[0];
//maybe a min woulde be better used here....
for (i = 0;i<arrayVals;i++){
if(tempval>array[i]){
tempval=array[i];
result=i;
}
}
return result;
}
//find the average of an array, this is only needed if there are multiple values being written to the
//scaning array
int Avg (int array[], int arrayVals){
int result;
int i = 0;
int sum;
for (i=0;i<=arrayVals;i++){
sum = array[i]+sum;
}
result = sum / arrayVals;
return result;
}
//reads the current distance
int GetDistance(){
int result = analogRead(ez1Pin);
if (result > 0){
result = result / 2;
}
return result;
}
//takes an array and appends the current distance at the end of it, moving all values and deleting the first
void loop() {
//Takes a sample from the Sonar and appends it to the distances array
i=0;
for(i=0;i<=SonarSamps;i++){
if (i==0){
distances[0]=distances[1];
}
else if(i==SonarSamps){
distances[i] = GetDistance();
}
else{
distances[i]=distances[i+1];
}
}
//end sampling and appending
AverageDistance=Avg(distances, SonarSamps+1);
MinimumDistance=MinVal(distances,SonarSamps);
Serial.print("[");
for (i=0;i<=SonarSamps;i++){
Serial.print(distances[i]);
Serial.print(", ");
}
Serial.print("]");
Serial.println();
Serial.print("The Mean is :");
Serial.print(AverageDistance);
Serial.print(" The Min is :");
Serial.print(distances[MinimumDistance]);
Serial.print(" , In position :");
Serial.print(MinimumDistance);
Serial.println();
delay(1000);
}