There are three main sorts of "average" used normally in Maths:
- Mean: This is the most common meaning of Average. It is the mathematical average of all the values in the set - the sum of all the values divided by the number of values.
- Mode: This is the "most common" value in a set of values. For the set {1, 2, 3, 4, 3, 5, 3, 1, 7, 3} the "mode" would be 3 since there are more 3's than any other number.
- Median: This is the middle value of a set of values. If there are 5 values and they are sorted into ascending order the "median" would be the third (middle) value.
By your comments it sounds like "mode" is what you are after - the most common number in your set of values.
It's quite easy to work out which is the most common number in a set if you are willing to loop through that set enough times.
I have an Average library that can do it for you. The main part of the mode()
function of that library looks like this:
most = _store[0];
mostcount = 1;
for(pos = 0; pos < _count; pos++) {
current = _store[pos];
currentcount = 0;
for(inner = pos + 1; inner < _count; inner++) {
if(_store[inner] == current) {
currentcount++;
}
}
if(currentcount > mostcount) {
most = current;
mostcount = currentcount;
}
// If we have less array slices left than the current
// maximum count, then there is no room left to find
// a bigger count. We have finished early and we can
// go home.
if(_count - pos < mostcount) {
break;
}
}
return most;
Basically two loops, one inside the other. The outer one steps through each number, and the inner one counts the number of times than number appears in the set (actually just from the current outer loop position to the end of the set - no point in counting numbers we've already looked at). If the count is greater than the current "mode" count then store that as the "mode" count and also store the value as the "mode" value. Move on to the next number.
To use the Average library it's quite simple:
const int micPin = A0;
// We want to be able to store 10 int values here.
Average <int>sounds(10);
void setup() {
Serial.begin(9600);
}
void loop() {
// Push 10 values into the Average buffer. Any old values will drop
// off the bottom.
for (int i = 0; i < 10; i++) {
sounds.push(analogRead(micPin));
}
Serial.print("Mode value is: ");
Serial.println(sounds.mode());
delay(1000);
}
soundArray[i] = micValue
is always storing the same number. You probably meansoundArray[i] = analogRead(micPin)
.