// The Barkley Music Maker.  This code is a modified version of the file/examples/digital/tone melody script.
// For more on tones:  http://www.arduino.cc/en/Tutorial/Tone


#include "pitches.h"  // This library should come with your Arduino Uno package.  You shouldn't need to download it.
//GPIO8 (The ultrasonic drier pin) is used by default by the tone melody library.  Define the buzzer driver on GPIO 9  as an input.  Make sure to add a jumper to the header locaed just under GPIO 9 on the shield
#define buzzer 9      // GPIO 9 DRIVES THE BUZZER

// The following are the notes in this melody in order.  Change it up as you see fit after you run the program once to hear the main tune.
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4 // These are the time durations between each note played.  Play around with these durations to get the hang of how it works, but not before running the program once.
};

void setup() {
  pinMode(buzzer,INPUT);  // Set the buzzer as an input.
}

void loop() {  // This will loop over and over again.
  playsong();  // Play the song by calling this function
  delay(5000); // Wait 5 seconds before playing again.
}  // This is the end of the main loop

void playsong(){ // Plays the 8 notes in order.  If yous song bas more than 8 notes, you'll need to change the FOR loop below accordingly.  You'll also need to add durations to the 'int noteDurations' array/list above.
  // iterate over the notes of the melody:
    for (int thisNote = 0; thisNote < 8; thisNote++) {  // This for loop plays 8 notes.  
    // to calculate the note duration, take one second divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);
    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    // stop the tone playing:
    noTone(8);
  }
}
