#include <Keypad.h>
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
  { '1', '2', '3', 'A' },
  { '4', '5', '6', 'B' },
  { '7', '8', '9', 'C' },
  { '*', '0', '#', 'D' }
};
float notes[] = {
  261.63,  // C4
  277.18,  // C#4
  293.66,  // D4
  311.13,  // D#4
  329.63,  // E4
  349.23,  // F4
  369.99,  // F#4
  392.00,  // G4
  415.30,  // G#4
  440.00,  // A4
  466.16,  // A#4
  493.88,  // B4
  523.25,  // C5
  554.37,  // C#5
  587.33,  // D5
  622.25,  // D#5
  659.26,  // E5
  698.46,  // F5
  739.99,  // F#5
  783.99,  // G5
  830.61,  // G#5
  880.00,  // A5
  932.33,  // A#5
  987.77,  // B5
  1046.50, // C6
  1108.73, // C#6
  1174.66, // D6
  1244.51, // D#6
  1318.51, // E6
  1396.91, // F6
  1479.98, // F#6
  1567.98, // G6
  1661.22, // G#6
  1760.00, // A6
  1864.66, // A#6
  1975.53, // B6
  2093.00, // C7
};
uint8_t colPins[COLS] = { 5, 4, 3, 2 }; // Pins connected to C1, C2, C3, C4
uint8_t rowPins[ROWS] = { 9, 8, 7, 6 }; // Pins connected to R1, R2, R3, R4
bool alternator;
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
  Serial.begin(9600);
  alternator = false;
}
void loop() {
  char key = keypad.getKey();
   if (key) {
    // Map the key to the corresponding note frequency index
    int index = mapKeyToIndex(key);
    if (index >= 0) {
      // Get the frequency of the note
      int frequency = notes[index];
      if (keypad.isPressed(key)) {
        alternator = !alternator;
        int speaker = alternator ? 10 : 11;
        tone(speaker, frequency, 100);
      }
    }
  }
}
// Map a keypad key to the corresponding note frequency index
int mapKeyToIndex(char key) {
  switch (key) {
    case '1': return 0;
    case '2': return 2;
    case '3': return 4;
    case 'A': return 5;
    case '4': return 7;
    case '5': return 9;
    case '6': return 11;
    case 'B': return 12;
    case '7': return 14;
    case '8': return 16;
    case '9': return 17;
    case 'C': return 19;
    case '*': return 21;
    case '0': return 23;
    case '#': return 24;
    case 'D': return 26;
    default: return -1;
  }
}