0

I have a project due in a day and I don't expect this question to be answered although it is a very simple one. I have a code which I used from the following site: http://dominikzeman.blogspot.co.nz/2016/12/we-are-number-one-but-its-arduino.html It's a simple code which plays the song "We are number one" through a piezo speaker however it loops the song which I need without a loop. I've tried various strategies (keep in mind that this is new to me) to stop the loop but I get errors every time.

Here is the code:

const int fn = 400;
const int hn = 200;
const int qn = 100;
const int f5 = 698;
const int c6 = 1047;
const int b5 = 988;
const int gh5 = 831;
const int ch6 = 1109;
const int dh6 = 1245;

int song[] = {
f5,fn + hn,
c6,hn,
b5,qn,
c6,qn,
b5,qn,
c6,qn,
b5,hn,
c6,hn,
gh5,fn,
f5,fn + hn,
f5,hn,
gh5,hn,
c6,hn,
ch6,fn,
gh5,fn,
ch6,fn,
dh6,fn,
c6,hn,
ch6,hn,
c6,hn,
ch6,hn,
c6,fn
};

void setup() {
Serial.begin(9600);
}

void loop() {

for (int i = 0; i < (sizeof(song)/sizeof(int)); i = i + 2){
tone(8, song[i]);
delay(song[i + 1]);
}

noTone(8);
delay(1000);

}

I do know that the problem is that there should be no code in void loop if I want it to stop however I cannot fix it without constant frustrating errors.

Any quick help would be a lifesaver.

Danny_ds
  • 11,201
  • 1
  • 24
  • 46
Matt
  • 1

1 Answers1

2

First, it would be better to isolate the code for playing the song in a separate function:

void PlaySong()
{
    for (int i = 0; i < (sizeof(song)/sizeof(int)); i = i + 2){
        tone(8, song[i]);
        delay(song[i + 1]);
    }
}

To play the song only once at startup, call it from setup():

void setup() {
    Serial.begin(9600); // not sure if you need this
    PlaySong();
}

To play the song when a botton is pressed or an input changes, you can test for that in loop(), and if pressed call the function once from there.

Danny_ds
  • 11,201
  • 1
  • 24
  • 46