DANGER! :o
The way you are coding will lead to overrunning your arrays. You will read/write the next variable after this one and/or hose your return stack. And in your summing, you might be adding an extra (possibly undefined) value.
You only get away with it in this code (and I'm not sure that you are getting away with it - in one place you call a function with sampSize + 1) because you made your array 1 more than your sampleSize. But they are not connected. What if you later modify one and forget the other?
This will help:
note: no "=" and no semicolon on the define line:
#define SonarSamps 10
int distances[SonarSamps];
Remember, an array in C goes from 0..size - 1;
for (i=0;i<=arrayVals;i++){
sum = array[i]+sum;
}
should be:
for (i=0;i<arrayVals;i++){
sum = array[i]+sum;
}
And
//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];
}
}
Should be:
//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];
}
}
Also, way too much wasted CPU time moving values (this part):
distances[i]=distances[i+1];
No need to move the data. Just move the insertion point:
distances[i++] = GetDistance();
if(i == SonarSamps)
i = 0;