char keypad [4][4] = {
{'1', '2', '3','A'},
{'4', '5', '6','B'},
{'7', '8', '9','C'},
{'*', '0', '#','D'}
};
char getKey() {
// set key value to null
char keyValue = '\0';
// a variable to read the row state
int rowState;
// for each pin 0-2 connected to COL1-3 do the following
for (int col = 0; col < 3; col++) {
// set the column HIGH
digitalWrite(col, HIGH);
// for each pin 3-6 connected to ROW1-4 do the following
for (int row = 3; row < 7; row++) {
// read the state of the row
rowState = digitalRead(row);
// if the state of the row is HIGH the do the following
if (rowState == HIGH) {
// set key value to the character
// corresponding to the pressed button
keyValue = (keypad[row - 3][col]);
}
}
// set the column back to LOW
digitalWrite(col, LOW);
}
// return the key value
return (keyValue);
}
// get key value
char key = getKey();
void setup() {
Serial.begin(9600);
// set pins 0-2 as outputs to control COL1-3 of the keypad
for (int col = 0; col < 3; col++) {
pinMode(col, OUTPUT);
}
// set pins 3-6 as inputs to read ROW1-4 of the keypad
for (int row = 3; row < 7; row++) {
pinMode(row, INPUT);
}
}
void loop() {
// if the key value is not NULL then
if (key != '\0') {
// display the key value on the serial monitor
Serial.println(key);
}
}