Thames & Kosmos Code Gamer Experiment Manual page 47

Coding workshop ? game with kosmobits
Table of Contents

Advertisement

PROJECT 14
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
set to 0. In the
loop, then, all the values saved in the
for
value[]
array are added to
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
in other words, that it is less than 0 or greater than 7.
That's why you will be correcting it with the
instruction in case of doubt.
Finally, the last
query checks whether the button is
if
pushed. If so, the corresponding note is output. If not, no
note is output.
Admittedly, this was a little more involved.
But the results make it all worthwhile!
CodeGamer manual inside english.indd 45
variable is first
average
. To calculate the
average
.
has an invalid value —
noteIndex
if-else
// 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;
// Total the measurement values.
for (int i = 0; i < N; ++i) {
average = average + 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);
}
}
CodeGamer
</>
// Start with the value 0
7/19/16 12:32 PM
45

Advertisement

Table of Contents
loading

Table of Contents