#define SPEAKER_PIN 2


#define  a3f    208     // 208 Hz
#define  b3f    233     // 233 Hz
#define  b3     247     // 247 Hz
#define  c4     261     // 261 Hz MIDDLE C
#define  c4s    277     // 277 Hz
#define  e4f    311     // 311 Hz    
#define  f4     349     // 349 Hz 
#define  a4f    415     // 415 Hz  
#define  b4f    466     // 466 Hz 
#define  b4     493     //  493 Hz 
#define  c5     523     // 523 Hz 
#define  c5s    554     // 554  Hz
#define  e5f    622     // 622 Hz  
#define  f5     698     // 698 Hz 
#define  f5s    740     // 740 Hz
#define  a5f    831     // 831 Hz 

#define  rest    -1

#define EIGHTH_NOTE 250
#define QUARTER_NOTE (EIGHTH_NOTE * 2)
#define HALF_NOTE (QUARTER_NOTE * 2)
#define WHOLE_NOTE (HALF_NOTE * 2)


#define SPEED_FACTOR 0.5

void playNote(int note, int duration) {
  if (note == rest) {
    delay(duration * SPEED_FACTOR);
  } else {
    tone(SPEAKER_PIN, note, duration * SPEED_FACTOR);
    delay(duration * SPEED_FACTOR + 50); 
  }
}

void setup() {
 
}

void loop() {
  
  int melody[] = {
    c5s,  e5f, e5f, f5, a5f, f5s, f5, e5f, c5s, e5f, rest, a4f, a4f,
    rest, c4s, c4s, c4s, c4s, e4f, rest, c4, b3f, a3f,
    rest, b3f, b3f, c4, c4s, a3f, a4f, a4f, e4f,
    rest, b3f, b3f, c4, c4s, b3f,  c4s, e4f, rest, c4, b3f, b3f, a3f,
    rest, b3f, b3f, c4, c4s, a3f, a3f, e4f,  e4f, e4f, f4, e4f,
    c4s, e4f, f4, c4s, e4f, e4f, e4f, f4, e4f, a3f,
    rest,  b3f, c4, c4s, a3f, rest, e4f, f4, e4f,
    b4f, b4f, a4f, a4f,
    f5, f5, e5f, b4f, b4f, a4f, a4f, e5f, e5f, c5s, c5, b4f,
    c5s, c5s, c5s, c5s,
    c5s, e5f, c5, b4f, a4f, a4f, a4f, e5f, c5s,
    b4f, b4f, a4f, a4f,
    f5,  f5, e5f, b4f, b4f, a4f, a4f, a5f, c5, c5s, c5, b4f,
    c5s, c5s, c5s, c5s,
    c5s, e5f, c5, b4f, a4f, rest, a4f, e5f, c5s, rest // Última pausa
  };

  
  int rhythm[] = {
    6, 10, 6, 6, 1, 1, 1, 1, 6, 10, 4, 2, 10,
    2, 1, 1, 1, 1, 2, 1, 1, 1, 5,
    1, 1, 1, 1, 3, 1, 2, 1, 5,
    1, 1, 1, 1, 1,  1, 1, 2, 1, 1, 1, 1, 3,
    1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4,
    5, 1, 1, 1,  1, 1, 1, 1, 2, 2,
    2, 1, 1, 1, 3, 1, 1, 1, 3,
    1, 1, 1, 1,
    3, 3, 6, 1, 1, 1, 1, 3, 3, 3, 1, 2,
    1, 1, 1, 1,
    3, 3, 3, 1, 2, 2, 2, 4, 8,
    1, 1, 1, 1,
    3, 3, 6, 1, 1, 1, 1, 3, 3, 3,  1, 2,
    1, 1, 1, 1,
    3, 3, 3, 1, 2, 2, 2, 4, 8, 4
  };

  
  for (int i = 0; i < sizeof(melody) / sizeof(melody[0]); i++) {
    playNote(melody[i], rhythm[i] * EIGHTH_NOTE);
  }
}