#include <Arduino.h>
#include <SPI.h>
#include <Wire.h>
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_D5 587
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_B5 988
#define REST 0
/*
+++++++++++++++++++++++++++++++++++++++
speaker
input voltage 5 V
+++++++++++++++++++++++++++++++++++++++
*/
#define speaker 6
// change this to make the song slower or faster
int tempo = 100;
void playMelody(int[],int);
// notes of the moledy followed by the duration.
// a 4 means a quarter note, 8 an eighteenth , 16 sixteenth, so on
// !!negative numbers are used to represent dotted notes,
// so -4 means a dotted quarter note, that is, a quarter plus an eighteenth!!
int melodyTheme[] = {
//game over sound
NOTE_C5,-4, NOTE_G4,-4, NOTE_E4,4, //45
NOTE_A4,-8, NOTE_B4,-8, NOTE_A4,-8, NOTE_GS4,-8, NOTE_AS4,-8, NOTE_GS4,-8,
NOTE_G4,8, NOTE_D4,8, NOTE_E4,-2,
};
int notesTheme = sizeof(melodyTheme) / sizeof(melodyTheme[0]) / 2;
int melodyGameOver[]= {NOTE_B5, 8, NOTE_F5, 8, REST, 8, NOTE_F5, 8, NOTE_F5, 4, NOTE_E5, 4, NOTE_D5, 4,
NOTE_C5, 8, NOTE_E5, 8, REST, 8, NOTE_E5, 8, NOTE_C4, -4, REST, -4};
int notesGameOver=sizeof(melodyGameOver) / sizeof(melodyGameOver[0]) / 2;
// sizeof gives the number of bytes, each int value is composed of two bytes (16 bits)
// there are two values per note (pitch and duration), so for each note there are four bytes
// this calculates the duration of a whole note in ms
int wholenote = 30000/50;
int divider = 0, noteDuration = 0;
void setup() {
Serial.begin(9600);
delay(100);
// iterate over the notes of the melody.
// Remember, the array is twice the number of notes (notes + durations)
playMelody(melodyGameOver, notesGameOver);
}
void loop() {
// no need to repeat the melody.
}
void playMelody(int melody[], int notes){
for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {
// calculates the duration of each note
divider = melody[thisNote + 1];
if (divider > 0) {
// regular note, just proceed
noteDuration = (wholenote) / divider;
} else if (divider < 0) {
// dotted notes are represented with negative durations!!
noteDuration = (wholenote) / abs(divider);
noteDuration *= 1.5; // increases the duration in half for dotted notes
}
// we only play the note for 90% of the duration, leaving 10% as a pause
tone(speaker, melody[thisNote], noteDuration*0.9);
// Wait for the specief duration before playing the next note.
delay(noteDuration);
// stop the waveform generation before the next note.
noTone(speaker);
delay(70);
}
}