Admittedly, this was a little more involved.
But the results make it all worthwhile!
// Raise the index by 1, so the next
// value can be saved at the next location
// in the values[] field.
++index;
// If index == N, the field is
// fully described.
// index is then set to 0, so that
// the oldest value
// is overwritten in the next pass.
if (index == N) {
index = 0;
}
// Now the average of the last N
// measurement readings is calculated.
int average = 0;
// Start with the value 0
// Total the measurement values.
for (int i = 0; i < N; ++i) {
average = a values[i];
}
// Divide the total by the number of values.
average = average / N;
int noteIndex = (average - measurementMin) /
scaling;
// noteIndex must not be less than 0 or
// greater than 7:
if (noteIndex < 0) {
noteIndex = 0;
} else if (noteIndex > 7) {
noteIndex = 7;
}
// Output note
if (digitalRead(buttonPin) == LOW) {
tone(buzzerPin, scale[noteIndex] * freqRoot);
delay(10);
} else {
noTone(buzzerPin);
delay(1);
}
}
</>
back to 0. The array is filled from the beginning again.
Then it’s a matter of determining the average of the last 10
measurements. To do that, the
average
variable is first
set to 0. In the
for
loop, then, all the values saved in the
value[]
array are added to
average
. To calculate the
average from that, the result has to be divided by the
number of values:
average = average / N;
.
With
int noteIndex = (average - measurementMin) / scaling;
,
you will be determining the “note index”: Which note in the
scale sequence should be played?
It might happen that
noteIndex
has an invalid value —
in other words, that it is less than 0 or greater than 7.
That’s why you will be correcting it with the
if-else
instruction in case of doubt.
Finally, the last
if
query checks whether the button is
pushed. If so, the corresponding note is output. If not, no
note is output.
45
CodeGamer
PROJECT 14
CodeGamer manual inside english.indd 45
7/19/16 12:32 PM