Problems with push buttons and speakers

Hi, I’m super new with Arduino (and programming as a whole…) but I’m trying to learn :slight_smile:

I have an Arduino Uno and I’m trying to use a three push buttons to sound three separate tones on an 8 ohm speaker. I couldn’t find a tutorial to match exactly what I needed so I pulled from a bunch of them to get kind of close ( I thought). But when I ran the sketch with the board I just get a bunch of noise and a slightly different tone when I press the middle button. This is what I have so far for my sketch, it looks right to me but I know it’s way off and I would like some help. (In case anyone is curious I’m trying to make it so I can use the button’s to play Harmonica’s theme from Once Upon a Time in the West)

#include “pitches.h”

int speakerPin = 8;

int buttonPins = {
0, 1, 2
};

int notes = {
NOTE_C5, NOTE_DS5, NOTE_E5
};

int buttonState = 0;

void setup() {

pinMode(buttonPins, INPUT);
}

void loop() {
for (int buttonPins = 0; buttonPins < 3; buttonPins++) {
int buttonState = digitalRead(buttonPins);

if (buttonState == HIGH) {
tone(8, notes[buttonPins], 20);
}
else{
noTone(8);
}
}
}

 pinMode(buttonPins, INPUT);

and

  int buttonState = digitalRead(buttonPins);

and

 tone(8, notes[buttonPins], 20);

Did you forget that buttonPins is an array ?

How are the buttons wired ?

I suggest that you use INPUT_PULLUP in the pinMode()s for the buttons and wire them to take the input LOW when pressed. This ensures that the inputs are always in a known state and are not floating at an uncertain voltage. You will also need to change the program logic to test for LOW to detect a button press.

I switched the pins to 2, 3, and 4. They are hooked up to 5 v and 10k resistors.

So should I switch

pinMode(buttonPins, INPUT);

with

pinMode(buttonPins, INPUT_PULLUP);

?

I knew I had them in an array but I’m not sure how to use an array properly. How do I change it to test for LOW voltage (I think this is why it’s making sound without a button press?)?

Thank you so much for your help :smiley: <3

How do I change it to test for LOW voltage

if (digitalRead(pinNumber) == LOW}
{
  //code to run when button is pressed
}

I’m not sure how to use an array properly

for (int x = 0; x < NUMBER_OF_PINS; x++)
{
  state = digitalRead(buttonPins[x];
}