Pressing a different buttons to play a tone using the buzzer

Hello! I'm trying to have the Arduino buzzer play a different tone depending on if 1 of three buttons are pressed. I'm having trouble with the loop as currently only the 1st button plays a tone when pressed while buttons 2 and 3 do not. I know the wiring is correct as individually the buttons work, so I think it's something with my code!:

const int button = 9; //buzzer to arduino pin 9
const int button2 = 10;
const int button3 = 11;

void setup(){

pinMode(button, OUTPUT); // Set buzzer - pin 9 as an output
pinMode(button2, OUTPUT);
pinMode(button3, OUTPUT);

}

void loop(){
int buttonstate = digitalRead(button);
int button2state = digitalRead(button2);
int button3state = digitalRead(button3);

if (buttonstate == LOW) { //if button 1 is pressed, play a tone at 1000HZ
  Serial.println("Button 1 is being pressed");
  tone(button, 1000);
  
  if (buttonstate == HIGH && button2state == LOW && button3state == HIGH) { // if button 2 is pressed and button 1 and 3 aren't play a tone at 500HZ
    Serial.println("Button 2 is being pressed");
    tone(button2, 500);
    
    if (buttonstate == HIGH && button2state == HIGH && button3state == LOW) { // if button 3 is pressed and button 1 and 2 aren't play a tone at 250HZ
      Serial.println("Button 3 is being pressed");
      tone(button3, 250);
    }
  }
} 
else { //No sound is played if a button isn't pressed
 noTone(button);
 noTone(button2);
 noTone(button3);
}

}

Please post your code using code tags.

The code below is an obvious problem: You have the if statements nested so the conditions for the last 2 if statements can never be met because buttonstate is LOW when those conditions are tested.

if (buttonstate == LOW) { //if button 1 is pressed, play a tone at 1000HZ
  Serial.println("Button 1 is being pressed");
  tone(button, 1000);
  
  if (buttonstate == HIGH && button2state == LOW && button3state == HIGH) { // if button 2 is pressed and button 1 and 3 aren't play a tone at 500HZ
    Serial.println("Button 2 is being pressed");
    tone(button2, 500);
    
    if (buttonstate == HIGH && button2state == HIGH && button3state == LOW) { // if button 3 is pressed and button 1 and 2 aren't play a tone at 250HZ
      Serial.println("Button 3 is being pressed");
      tone(button3, 250);
    }
  }
} 

I would recommend else if statements.

I would like to see your wiring because you are using pins 9,10, and 11 for both input and output!

Can't possibly be working that way...

looks like all your cases are conditional on your first button and sub-conditional statement within that condition are defeated because they are conditioned on buttonState == HIGH

Ahh ok thank you!

Post your latest code and we'll go from there.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.