Hi everyone,
(I'm new with Arduino (opened my starter-kit yesterday :P), so don't expect to much expertise from my side ;))
I have a problem with my code. I wrote this:
int speakerPin = 11; // the pin where the speaker or buzzer is attached to (doesn't need to be pwm~ pin)
int bpm = 120; // beats per minute
float length = 1; // the exact duration of the current note (in ms) (unset)
int n_notes = 116; // the total number of notes
char notes[] = "IODXZDZbbZDDZbZXIOXIZXbZbXIOXIZXbDXDZbZDbZXIZDZbZbZIODXZDZbbZDDZbZXIOXIZXbZbXIOXIZXbDXDZbZDbZXIZDZbZbZbiobioBZXZEXEI"; // notes to play
float beat[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // the relative duration of those notes (quarter note, full note, etc.)
// notes with frequencys
// rest c c# d d# e f f# g g# a a# b c c# d d# e f f# g g# a a# b c c# d d# e f f# g g# a a# b c
char notename[] = { ' ', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 'c', 'z', 'd', 'x', 'e', 'f', 'i', 'g', 'o', 'a', 'p', 'b', 'C', 'Z', 'D', 'X', 'E', 'F', 'I', 'G', 'O', 'A', 'P', 'B', '!' };
int freqs[] = { 0, 130, 138, 146, 155, 164, 174, 184, 195, 207, 220, 233, 246, 261, 277, 293, 311, 329, 349, 370, 391, 415, 440, 466, 493, 523, 555, 587, 622, 659, 698, 740, 783, 832, 880, 933, 987, 1046 };
// set pin as output
void setup() {
pinMode(speakerPin, OUTPUT);
}
void loop() {
// start for one note the loop
for (int i=0; i<n_notes; i++) {
length = floor(240/(bpm*4)*1000*beat[i]); // set the duration in ms for the note
// get the frecuency
for (int j=0; j<38; j++) {
if (notename[j]==notes[i] && notename[j]!=' ') {
tone(speakerPin, freqs[j]); // play the note
}
}
delay((floor(240/(bpm*4)*1000*beat[i]))-75); // wait to stop the note (to be it a lil' bit more realistic)
noTone(speakerPin); // stop the note
delay(75); // wait a short while
}
}
It's a Nyan Cat play-app (and the nyansong-part is unfinished yet). Sorry for all the comments in the code btw. But the problem is that if I set the bpm 61 or higher, it only plays "beeeeeeeeeeeeeeeeeeeeeeeeeeeeeep..." from the first note, and plays nothing more, but when I set beat to 0.5 and bpm to 60, it plays correctly twice as fast. What's wrong with my code?
Solve: Set everything what's related to length to a floating point number, thanks to PaulS!