#include "pitches.h"
#include <wiringPi.h>


// notes in the melody:
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 };

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

// speaker Pin - wiringPi pin 0 is BCM_GPIO 17
const int speaker = 0;

void playTone(int note, int duration) {
  // note is the tone frequency in cyles per second, duration is 
  // the length of time the note is played in milliseconds.
  // Playtone() outputs a square wave at the input frequency.
  long stopTime = duration * 1000L;   // note duration in microseconds
  int period = (int)(1000000L / note);   // period in microseconds
  int pulseLength = (int)(1000000L / (2*note));  // one half the period
  long time;

  if(duration > 0 && note > 0) {
    for (time = 0; time < stopTime; time+=period) {
      digitalWrite(speaker, HIGH);   
      delayMicroseconds(pulseLength);
      digitalWrite(speaker, LOW);
      delayMicroseconds(pulseLength);
    }
  }
}

void setup() {
  wiringPiSetup ();                      
  pinMode(speaker, OUTPUT);
}

int main (void) {
  int thisNote;
  setup();	

  // iterate over the notes of the melody:
  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.
    int 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:
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
  }
  digitalWrite(speaker, LOW); 
  return 0 ;
}
