1

I am trying to create a sketch that utilizes two arrays, one array to hold five buttons as input, assigned to pins, and another array to hold five musical notes. I have attached a RGB LEDs with pull-down resistors and attached a 8 ohms resistor speaker.

The code is as followed:

 //Pentatonic Piano
 // C D E G A

 #define NOTE_C   262 //HZ
 #define NOTE_D   294 //HZ
 #define NOTE_E   330 //HZ
 #define NOTE_G   392 //HZ
 #define NOTE_A   440 //HZ

 const int SPEAKER = 9;   //speaker on pin 10
 const int BLED = 10;      //Blue LED on pin 9
 const int GLED = 6;      //Green LED on pin 6
 const int RLED = 5;      //Red LED on pin 3

 int buttonState = 0; 

 //Button Array
 int Buttons[]= {11, 8, 7, 4, 3};

 //Tone Note Array
 int Notes[] = {NOTE_C, NOTE_D, NOTE_E, NOTE_G, NOTE_A};

 void setup()
 {
 pinMode(BLED, OUTPUT);
 pinMode(GLED, OUTPUT);
 pinMode(RLED, OUTPUT);
 pinMode(Buttons, INPUT);
 }


 void loop()
 {

   buttonState = digitalRead(Buttons);

   if (buttonState = Buttons[0])
   { tone(SPEAKER, Notes[0]);
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, HIGH);

   }
   else if (buttonState = Buttons[1])
   {tone(SPEAKER, Notes[1]);
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, HIGH);
    digitalWrite(RLED, LOW);
   }
   else if (buttonState = Buttons[2])
   {tone(SPEAKER, Notes[2]);
    digitalWrite(BLED, HIGH);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, LOW);

   }
   else if (buttonState = Buttons[3])
   {tone(SPEAKER, Notes[3]);
    analogWrite(BLED, 127);
    analogWrite(GLED, 0);
    analogWrite(RLED, 127);

   }
   else if (buttonState = Buttons[4])
   {tone(SPEAKER, Notes[4]);
    analogWrite(BLED, 0);
    analogWrite(GLED, 127);
    analogWrite(RLED, 127);

   }

   else
   {
    digitalWrite(BLED, LOW);
    digitalWrite(GLED, LOW);
    digitalWrite(RLED, LOW);
    noTone(SPEAKER);
   }
 }

The problem is no matter what button I press, the RGB only emits a green light and there is absolutely no sound coming from the speaker. I am truly stumped.

0

First, these statements:

if (buttonState = Buttons[0])

are doing an assignment, not a test for equality. You want:

if (buttonState == Buttons[0])
//               ^Notice

Next, pinMode takes two integers, but you are passing an array. You can use a loop to call pinMode multiple times:

for (int i = 0; i < sizeof(Buttons) / sizeof(Buttons[0]); i++) {
     pinMode(Buttons[i], INPUT);
}

Same goes for digitalRead(). You need to read the state for each button:

buttonState = digitalRead(Buttons[0]);
if (buttonState == HIGH) {
   ....
}
buttonState = digitalRead(Buttons[1]);
if (buttonState == HIGH) {
   ....
}
//etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.