change tone sounds by altering the waveforms

Dependencies:   mbed

Fork of 5_songs by MakingMusicWorkshop

Revision:
7:4730853634bf
Parent:
6:406f73a0eb49
Child:
8:77227ecac915
--- a/main.cpp	Wed May 18 18:45:55 2016 +0000
+++ b/main.cpp	Sat May 21 16:07:43 2016 +0000
@@ -11,14 +11,51 @@
 
 // this is our function that plays a tone. 
 // Takes in a tone frequency, and after duration (in ms.) we stop playing again
-static void play_tone(int tone) {
-    buzzer.period_us(1000000/(tone));
-    buzzer.write(0.10f); // 10% duty cycle, otherwise it's too loud
+static void play_tone(int tone, int duration) {
+
+   int tone_period_us = 1000000/tone;
+    
+   for (long i = 0; i < duration * 1000L; i += tone_period_us * 2) {
+
+        // let's change the buzzer's volume depending on how far we are
+        float pct = (float)i / (float)(duration * 1000L);
+
+        buzzer = (1 - pct) / 4; // high to low
+        wait_us(tone_period_us);
+        buzzer = 0.0f;
+        wait_us(tone_period_us);
+    }
+
 }
 
 static void play_song(int notes_left, int* melody, int* duration) {
     
-    // YOUR CODE HERE
+   // melody and duration are pointers, they point to the array of tones and durations we declared earlier
+    // every time we play a note we up these pointers (move one element forward)
+    // so the current tone is always the first element of melody (same for duration)
+ 
+    int length;
+ 
+    while(notes_left > 0)
+    {
+ 
+        int tone = melody[0];
+        // BPM is quarter notes per minute, so length in milliseconds is:
+        length = static_cast<int>(static_cast<float>(1000 / duration[0]) * (60000.0f / static_cast<float>(BPM * 1000)));
+ 
+        play_tone(tone, length);
+                    
+        // after the full length of this tone, we up the melody, and down the notes_left
+        
+        notes_left--;
+        melody++;
+        duration++;
+            
+    }  
+ 
+    // we're done! just finish this note and silence
+    wait_ms(length / 2);  
+    silence();  
 
 }
 
@@ -39,8 +76,7 @@
         16, 16, 16, 16, 16, 16, 16, 
         16, 16, 16, 16, 16 
     };    
-
-    
+     
     // melody & duration are on the heap, need to get them on the stack
     int *m = new int[sizeof(melody) / sizeof(int)];
     memcpy(m, melody, sizeof(melody));