2

//Here is my code so far

int speakerPin = 9;

int length = 28; 

char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

int tempo = 150;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

   digitalWrite(speakerPin, HIGH);

   delayMicroseconds(tone);

   digitalWrite(speakerPin, LOW);

   delayMicroseconds(tone);

}

}

void playNote(char note, int duration) {

char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',           

                 'c', 'd', 'e', 'f', 'g', 'a', 'b',

                 'x', 'y' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                 956,  834,  765,  593,  468,  346,  224,

                 655 , 715 };

int SPEE = 5;


for (int i = 0; i < 17; i++) {

   if (names[i] == note) {
    int newduration = duration/SPEE;
     playTone(tones[i], newduration);

   }

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

void loop() {

for (int i = 0; i < length; i++) {

   if (notes[i] == ' ') {

     delay(beats[i] * tempo);

   } else {

     playNote(notes[i], beats[i] * tempo);

   }


   delay(tempo);

}

}
5

Assuming, the program can stop after playing 6 times, put another for loop in the loop function:

void loop() 
{
   for (int nTimes = 0; nTimes < 6; nTimes++)
   {
      // Existing loop code
   } 

   while(true) {};
}

A less crude way is to create a global variable:

int _timesPlayed = 0;

And change the for loop:

void loop() 
{
   if (_timesPlayed < 6)
   {
      // Existing loop code

     _timesPlayed++;
   }
}
2
  • In most programming contexts, creating a global variable to represent a loop-counter would be considered very crude (rather than less crude), as it's unnecessarily hoisting the scope of the loop-counter from the for-block to not even just the method-scope, but the global-scope. Is there a special reason that this might be a good thing in Arduino? – Nat Mar 9 at 12:08
  • @Nat: The benefit of making items global is that it will show up in the summary of compiling so that it shows the amount of used SRAM. Also, some libraries use global defined variables (including those libraries is enough). And if a variable is global, you can access it anywhere (which is not so maintainable, but easy), but by passing parameters the stack is filled which also counts toward the amount of SRAM, although this should be ignorable (passing structs or buffers, not by pointer/reference is not a good idea anyway). – Michel Keijzers Mar 9 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.