![Thames & Kosmos Code Gamer Experiment Manual Download Page 45](http://html1.mh-extra.com/html/thames-and-kosmos/code-gamer/code-gamer_experiment-manual_1099224045.webp)
</>
Musical scale
YOU WILL NEED
› KosmoDuino in the interaction board
THE PLAN
Your KosmoDuino will play a musical scale.
THE PROGRAM
First you include the
KosmoBits_Pins.h
file and define
the
buzzerPin
and
freqRoot
constants. Finally, you
apply the
scale[]
array, in which the frequency
relationships of the notes of a major-key scale will be
placed. To determine the frequency of a note, you will
have to multiply the corresponding value by the frequency
of the root chord.
#include <KosmoBits_Pins.h>
const int buzzerPin = KOSMOBITS_BUZZER_PIN;
const int freqRoot = 220;
// This is the
// note A (one octave deeper than the standard
// pitch A from project 10).
float scale[] = {1.f, 9.f/8, 5.f/4, 4.f/3, 3.f/2,
5.f/3, 15.f/8, 2.f};
void setup() {
for (int i = 0; i < 8; ++i) {
tone(buzzerPin, scale[i] * freqRoot);
delay(500);
}
noTone(buzzerPin);
}
void loop() {
// Nothing is done here.
}
This time, everything is happening in
setup()
. In the
for
loop, the variable
i
is counted up from 0 to 7. For each
value of
i
then, the
i
-th note of the scale is output with
tone(buzzerPin, scale[i] * freqRoot);
. As
described above, the frequency of the root chord
freqRoot
is multiplied by the corresponding frequency
relationship
scale[i]
to determine the right frequency.
After a pause, the
for
loop is passed through again until
the highest note of the scale is reached. Then it’s quiet:
noTone(buzzerPin);
.
This time, nothing is done in the main loop. The scale is just
played through a single time, in other words. To make the
scale play again, you can press the reset button on the
KosmoDuino. That will reset the code and carry it out
again from the beginning.
43
PROJECT 13
CodeGamer
CodeGamer manual inside english.indd 43
7/19/16 12:32 PM