Playing notes on the Passive Buzzer using an input (Membrane Keypad)

Hey everyone,

I'm trying to learn how to make my own midi device so I figured a good start would be to using the passive buzzer as an instrument controlled by an input. For this I'm using the membrane keypad as an input, so I copied the code from that program in the tutorial.

So far this is my code:

#include "Keypad.h"
#include "pitches.h"
int duration = 500;  // 500 miliseconds
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {9,8,7,6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {2,3,4,5}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); 

void setup(){
  Serial.begin(9600);
}
  
void loop(){
  char customKey = customKeypad.getKey();
  if (customKey){
    Serial.println(customKey);
  }
  if (customKey = "A"){
    tone(10, NOTE_C3, duration);
  }
}

If I open up Serial Monitor I see that the Membrane Keypad is working correctly, but I can't get the buzzer to respond correctly. When I upload this code the buzzer just constantly plays a C3 note, but how I want it to actually operate is that if I hit the A button I'll play the C3 note for 500 ms.

How do I properly read the customKey value and get it to output the right note? Also, this example just shows one case, but I have 16 keypad values and want to output 16 notes, is there an easier way to go about this than 16 IF statements?

This:

  if (customKey = "A"){

should be:

  if (customKey == 'A'){

Comparison is == not =. = is assignment.

customKey is a single character so you must compare it to a character not a string.

is there an easier way to go about this than 16 IF statements?

a switch() - case would work, or you could create an Array of your notes, and play them according to the input value.

ToddL1962:
This:

  if (customKey = "A"){

should be:

  if (customKey == 'A'){

Comparison is == not =. = is assignment.

customKey is a single character so you must compare it to a character not a string.

Great advice, this worked. It's these small little knacks that are really tripping me up in programming, but with every mistake I'm learning.