small problem

I have a problem in my code, but what?

my button does not work

 #include "pitches.h"


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 };
  
int switchState =0;

void setup() {
pinMode(2, INPUT);
}

void loop() {
switchState = digitalRead(2);
if (switchState == HIGH) {  

  for (int thisNote = 0; thisNote < 8; thisNote++) {


    int noteDuration = 1000/noteDurations[thisNote];
    tone(8, melody[thisNote],noteDuration);

    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);

    noTone(8);
  }
}
else {
}
}

Is the button connected to the right pin? do you have a voltmeter to check that?

if you remove the button test from the code does it do as expected?

Sorry i'm a beginner, what is a button "test"?

switchState = digitalRead(2);
if (switchState == HIGH) {

Button test.

Yes, without the button test, it works.

Make these changes:

Connect the switch so when closed, the pin connects to Gnd.

Enable the internal pullup resistor: pinMode(2, INPUT_PULLUP);

Test to see to if button is pressed and the pin connected to Gnd: if (switchState == LOW) {

Dont work:

 #include "pitches.h"


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 };
  
int switchState =0;

void setup() {
pinMode(2, INPUT_PULLUP);
}

void loop() {
switchState = digitalRead(2);
if (switchState == LOW) {

  for (int thisNote = 0; thisNote < 8; thisNote++) {


    int noteDuration = 1000/noteDurations[thisNote];
    tone(8, melody[thisNote],noteDuration);

    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);

    noTone(8);
  }
}
else {
}
}

Add this line into setup()

Serial.begin(9600)

Add these lines right after the tone() statement.

      Serial.print(melody[thisNote]);
      Serial.print(" ");
      Serial.println (1000/noteDurations[thisNote]);

It works for me. I didn't have a speaker handy to test with, but the Serial.print statements show me that the code is executing as it should.

this is the output:

262 250 196 125 196 125 220 250 196 250 0 250 247 250 262 250

Just to clarify, your switch shoule be wired as follows:

GND____/ ____Pin 2