#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'}, // 1st row
{'4', '5', '6', 'B'}, // 2nd row
{'7', '8', '9', 'C'}, // 3rd row
{'*', '0', '#', 'D'} // 4th row
};
int tones[ROWS][COLS] = { // a frequency tone for each button
{31, 93, 147, 208},
{247, 311, 370, 440},
{523, 587, 698, 880},
{1397, 2637, 3729, 4978}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6,7,8,9}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
byte ledPin = 13;
boolean blink = false;
boolean ledPin_state;
void setup(){
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // Sets the digital pin as output.
digitalWrite(ledPin, HIGH); // Turn the LED on.
ledPin_state = digitalRead(ledPin); // Store initial LED state. HIGH when LED is on.
keypad.addEventListener(keypadEvent); // Add an event listener for this keypad
}
void loop(){
char key = keypad.getKey();
int freq = 0;
if (key){ // if a button is pressed
for (byte j=0; j<ROWS; j++) {
for (byte i=0; i<COLS; i++) {
if (key == keys[j][i]) { // found it, get the corresponding tone
freq=tones[j][i];
}
} // end i loop
} // end j loop
}
}
// Taking care of some special events.
void keypadEvent(KeypadEvent key){
int freq = 0;
if (key){ // if a button is pressed
for (byte j=0; j<ROWS; j++) {
for (byte i=0; i<COLS; i++) {
if (key == keys[j][i]) { // found it, get the corresponding tone
freq=tones[j][i];
}
} // end i loop
} // end j loop
}
switch (keypad.getState()){
case PRESSED:
if (key) {
tone(10,freq,5000);
Serial.print(key);
Serial.println(" pressed") ; // Remember LED state, lit or unlit.
}
break;
case RELEASED:
if (key) {
noTone(10);
Serial.print(key);
Serial.println(" released") ;
}
break;
case HOLD:
if (key) {
tone(10,freq);
Serial.print(key);
Serial.println(" held") ;
}
break;
}
}