#include "pitches.h"
#define NO_SOUND 0 // für die Pausen
int ldrPin = A0; // Lichtempfindlicher Widerstand
int speakerPin = 8; // Lautsprecher
// Thanks to
// http://garagelab.com/profiles/blogs/how-to-use-tone-function-arduino-playing-the-james-bond-theme
// Array mit Noten des Bond Theme
int16_t melody[] = {
NOTE_E4,NOTE_F4,NOTE_F4,NOTE_F4,NOTE_F4,NOTE_E4,NOTE_E4,NOTE_E4,
NOTE_E4,NOTE_G4,NOTE_G4,NOTE_G4,NOTE_G4,NOTE_E4,NOTE_E4,NOTE_E4,
NOTE_E4,NOTE_F4,NOTE_F4,NOTE_F4,NOTE_F4,NOTE_E4,NOTE_E4,NOTE_E4,
NOTE_E4,NOTE_G4,NOTE_G4,NOTE_G4,NOTE_G4,NOTE_E4,NOTE_E4,NOTE_E4,
NOTE_DS5,NOTE_D5,NOTE_B4,NOTE_A4,NOTE_B4,
NOTE_E4,NOTE_G4,NOTE_DS5,NOTE_D5,NOTE_G4,NOTE_B4,
NOTE_B4,NOTE_FS5,NOTE_F5,NOTE_B4,NOTE_D5,NOTE_AS5,
NOTE_A5,NOTE_F5,NOTE_A5,NOTE_DS6,NOTE_D6,NO_SOUND
};
// Dauer der einzelnen Noten
// Notenwert: 1 = ganze Note, 2 = halbe Note, 4 = Viertelnote usw.
int16_t noteDurations[] = {
8,16,16,8,4,8,8,8,
8,16,16,8,4,8,8,8,
8,16,16,8,4,8,8,8,
8,16,16,8,4,8,8,8,
8,2,8,8,1,
8,4,8,4,8,8,
8,8,4,8,4,8,
4,8,4,8,3,1
};
int songPace = 1450; // Dauer einer ganzen Note in Millisekunden
int melodyLength = 0;
int playState = 0; // 0 = ruhig warten bis es hell wird, 1 = Song spielt gerade, -1 = ruhig, warten bis es dunkel wird
int noteCount = 0; // Laufender Zaehler fuer aktuelle Position
void setup() {
Serial.begin(9600);
pinMode(speakerPin, OUTPUT);
melodyLength = sizeof(melody) / sizeof(melody[0]);
Serial.print ("Melody length: ");
Serial.println (melodyLength);
Serial.println ("------------");
}
void loop() {
if (analogRead(ldrPin) > 100) { // es ist grade hell!
if (playState == 0) { // warte ich gerade aufs loslegen?
playState = 1; // ja, also loslegen!
}
} else // es ist grade dunkel
{
// Spiele ich gerade oder warte ich darauf, dass es dunkel wird?
if ((playState == 1) || (playState == -1)) {
playState = 0; // Setze Status auf 0 = Warten, bis es hell wird
noteCount = 0;
}
}
if (playState == 1) {
int duration = songPace/noteDurations[noteCount]; // Aus Notenwert die Länge in Millisec berechnen
tone(speakerPin, melody[noteCount], duration); // Note mit tone() spielen
delay(duration*1.2); // Kurz warten vor naechster Note
noteCount ++; // Notenzaehler erhoehen
if (noteCount >= melodyLength) { // Wenn letzte Note gespielt, Zaehler auf Anfang und Status auf Pause
noteCount = 0;
playState = -1;
}
}
// Debug-Ausgaben auf dem Seriellen Monitor
Serial.print(playState);
Serial.print(" ");
Serial.print(noteCount);
Serial.print(" ");
Serial.print(melody[noteCount]);
Serial.print(" ");
Serial.print(noteDurations[noteCount]);
Serial.print(" ");
Serial.println(analogRead(A0));
} |