Skip to content

Commit a8bb65f

Browse files
Create note_dance.ino
1 parent bc916d9 commit a8bb65f

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

examples/note_dance/note_dance.ino

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Volume3 Music Example
3+
by Connor Nishijima
4+
5+
Picks a random note from a C Major scale to play,
6+
switches between volume-envelope and normal tone()
7+
behavior every 20 notes played.
8+
*/
9+
10+
#include "Volume3.h" // Import the magic juju
11+
12+
#define speakerPin 9 // Connect a speaker from Pin 9 to GND
13+
14+
bool useVol = true; // Are we using volume envelopes?
15+
byte noteCount = 0; // Keeps track of notes played so far
16+
17+
unsigned int scale[9] = {131, 165, 196, 262, 330, 392, 523, 659, 784}; // C Major scale in 3 octaves
18+
byte lastNote = 255; // Stores the last note played
19+
20+
void setup() {
21+
// Nothing needed here!
22+
}
23+
24+
void loop() {
25+
byte note = random(0, 9); // Pick a random note from the scale array
26+
27+
while (note == lastNote) { // We don't want repeat notes, try again until we find a new one
28+
note = random(0, 9);
29+
}
30+
31+
int frequency = scale[note]; // Set tone frequency based on the note we picked
32+
int volume = 1023; // Start volume at full 10-bit 1023 value
33+
34+
if (useVol == true) {
35+
// Play the note, and fade it out quickly
36+
while (volume > 0) {
37+
vol.tone(speakerPin, frequency, volume);
38+
volume -= 10;
39+
delay(2);
40+
}
41+
}
42+
else {
43+
vol.tone(speakerPin, frequency, 1023); // Just use max volume here
44+
delay(110);
45+
vol.noTone();
46+
delay(110);
47+
}
48+
49+
noteCount++;
50+
if (noteCount % 20 == 0) { // If we've played 20 notes, switch between tone modes
51+
useVol = !useVol;
52+
}
53+
54+
lastNote = note; // Remember the note we picked for next run
55+
}

0 commit comments

Comments
 (0)