New melody on button press

Hey!

I'm currently working on a project that has to do the following:

  1. You upload the code and a melody starts playing.
  2. You press the button (while the first melody is still playing) and the second melody has to start playing (first melody stops).
  3. Your press the button again (while the second melody is still playing) and the third melody has to start playing (second melody stops).

I have managed to read the button state while the song is playing, so now I want to play another melody (in my code for test purposes it is just a tone()) when I press that button.
The problem is, that the tone only plays for the moment that I press the button, and I want it so that when I press the button once and I release my finger, the tone keeps playing.

int piezoPin = 10;
int button1Pin = 8;
int button2Pin = 9;
int lastButton1State = 0;
int lastButton2State = 0;

unsigned long currentMillis;
unsigned long previousMillis = 0;

int melody[] = {NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4};
int noteDurations[] = {4, 8, 8, 4, 4, 4, 4, 4};


void setup() {
  Serial.begin(9600);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(piezoPin, OUTPUT);
  pinMode(potPin, INPUT);
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);
}

void loop() {
  int thisNote = 0;
  while (thisNote < 8) {
    int readButton1 = digitalRead(button1Pin);
    int readButton2 = digitalRead(button2Pin);
    if (readButton1 == 0) {
      currentMillis = millis();
      int noteDuration = 1000 / noteDurations[thisNote];
      int pauseBetweenNotes = noteDuration * 1.30;
      if (currentMillis - previousMillis > pauseBetweenNotes) {
        tone(piezoPin, melody[thisNote], noteDuration);
        previousMillis = currentMillis;
        thisNote++;
      }
    } else {
      tone(piezoPin, 700);
    }
  }
}

So how do I make it that when I press the button, the melody stops and the tone starts playing?

Thanks in advance! :slight_smile:

delete post