
#define DEFAULT_BAUDRATE 57600
#include "pitches.h"
#include "pic24_all.h"

/*
A simple program that drives a speaker attached to port RB14 using
the note-frequency correspondances defined in pitches.h.  It 
sends a square wave of the appropriate frequency to the speaker 
generating the corresponding tone (i.e., note).  The square wave is 
simply a high-low pulse.  The duration of the high and low pulse is
calculated from the tone frequency as follows:

      pulseLength = period / 2 = 1 / (2 * toneFrequency)

It's best to express the pulselength in microseconds.
*/

#define CONFIG_SPEAKER()  CONFIG_RB14_AS_DIG_OUTPUT()
#define SPEAKER  _LATB14    //_LATB14 is port register for RB14

// the prototype for the procedure that sends the high-low pulses 
// for each note to the speaker.
void playTone(uint16, uint32);

int main(void) {

  configClock();
  CONFIG_SPEAKER();
  SPEAKER = 0;

// the notes in the song to be played using the definitions in pitches.h
  uint16 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.:
  uint16 noteDurations[] = {4, 8, 8, 4, 4, 4, 4, 4 };

// number of notes in the melody array
  uint16 numberNotes = 8; 

  uint16 thisNote ;
  uint16 noteDuration;
  uint16 pauseBetweenNotes;

  // iterate over the notes in the melody array:
  for (thisNote = 0; thisNote < numberNotes; thisNote++) {

    // to calculate the note duration, take one second, expressed 
    // in milliseconds, divided by the note type.
    // e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    noteDuration = 1000/noteDurations[thisNote];

    playTone(melody[thisNote], noteDuration);

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    pauseBetweenNotes = noteDuration * 1.30;

    DELAY_MS(pauseBetweenNotes);
  }
  return 0;
}

void playTone(uint16 tone, uint32 duration) {
// tone is the tone frequency in cyles per second
// duration is the length of time the tone is played
// in milliseconds
// WRITE THIS PROCEDURE
// HINT: work in microseconds and use a for-loop

}



