Reputation: 676
I have an int array of melodies. If i press the button it plays the whole song but if i put a break after the delay
, than it just reset the i
. How do i make it so that only after another button-press it continues? (i'm still a newbie at this sorry and thanks in advance)
int buttonPin = 12;
void setup()
{
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
}
void loop()
{
// put your main code here, to run repeatedly:
int buttonState = digitalRead(buttonPin);
for(int i = 0; i < sizeof(mariomelody); i++)
{
if(buttonState == HIGH)
{
tone(8, mariomelody[i], 70);
delay();
}
}
}
Upvotes: 2
Views: 2446
Reputation: 98436
I'm guessing that you want to play the melody while the button is pressed, and stop if the button is released.
Then it would be something like:
int i = 0;
void loop()
{
if(digitalRead(buttonPin) == HIGH)
{
tone(8, mariomelody[i], 70);
i = (i + 1) % sizeof(mariomelody);
delay();
}
}
To avoid resetting the position to the begin of the melody you need i
to be a global variable.
If you want the button to switch on and off the melody you'll need another global variable playing
:
bool playing = false;
void loop()
{
if(digitalRead(buttonPin) == HIGH)
{
playing = !playing;
while (digitalRead(buttonPin) == HIGH)
; //wait for release
}
if (playing) {
//the rest is the same
}
}
Upvotes: 0
Reputation: 3753
Stop the loop while the button press is still held in:
int buttonPin = 12;
void setup()
{
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
}
void loop()
{
// put your main code here, to run repeatedly:
int buttonState = digitalRead(buttonPin);
for(int i = 0; i < sizeof(mariomelody); i++)
{
if(buttonState == HIGH)
{
tone(8, mariomelody[i], 70);
delay();
}
while(digitalRead(buttonPin) == HIGH)
{
// wait until the button is released
}
while(digitalRead(buttonPin) == LOW)
{
//wait until the button is pressed again
}
}
}
Upvotes: 1