2

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();
    }  
  }
}
4
  • This might not be an answer but your button might be high as default. Post code where you set up digital pin. Commented Feb 13, 2019 at 13:24
  • @Gox If it was, than the melody would be played immediately... Commented Feb 13, 2019 at 13:28
  • i dont have arduino with me, but my advice is always put this digitalWrite(buttonPin, LOW); in setup. also try putting it before if statement. Commented Feb 13, 2019 at 13:32
  • Now I get your quesiton Commented Feb 13, 2019 at 15:30

2 Answers 2

1

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
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.