#include <Keypad.h>
const uint8_t ROWS = 4;
const uint8_t COLS = 3;
char keys[ROWS][COLS] = {
{ '1', '2', '3'},
{ '4', '5', '6'},
{ '7', '8', '9'},
{ '*', '0', '#'}
};
uint8_t colPins[COLS] = {4, 3, 2};
uint8_t rowPins[ROWS] = {8, 7, 6, 5};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
struct Description {
char key;
const char * choices;
};
Description t9Map[] = {
{'0', "0"},
{'1', "1"},
{'2', "ABC2"},
{'3', "DEF3"},
{'4', "GHI4"},
{'5', "JKL5"},
{'6', "MNO6"},
{'7', "PQRS7"},
{'8', "TUV8"},
{'9', "WXYZ9"},
{'*', "*"},
{'#', "#"},
};
enum : byte {WAITING, KEYPRESS} state = WAITING;
char getKey() {
static byte currentKeyIndex = 0;
static Description* currentMap = nullptr;
char currentKey = keypad.getKey();
static uint32_t t0;
char finalKey = NO_KEY;
switch (state) {
case WAITING:
if (currentKey != NO_KEY) {
t0 = millis();
currentKeyIndex = 0;
state = KEYPRESS;
if (currentKey == '#') currentMap = &t9Map[11];
else if (currentKey == '*') currentMap = &t9Map[10];
else currentMap = &t9Map[currentKey - '0'];
Serial.write('(');
Serial.write(currentMap->choices[currentKeyIndex]);
Serial.write(')');
}
break;
case KEYPRESS:
if (currentKey != NO_KEY) {
if (currentKey == currentMap->key) {
// same key again, get next representation
t0 = millis();
if (++currentKeyIndex >= strlen(currentMap->choices)) currentKeyIndex = 0;
Serial.write('(');
Serial.write(currentMap->choices[currentKeyIndex]);
Serial.write(')');
} else {
// new key, validate the previous one and be ready for that one
finalKey = currentMap->choices[currentKeyIndex];
Serial.write('[');
Serial.write(finalKey);
Serial.write(']');
t0 = millis();
currentKeyIndex = 0;
if (currentKey == '#') currentMap = &t9Map[11];
else if (currentKey == '*') currentMap = &t9Map[10];
else currentMap = &t9Map[currentKey - '0'];
Serial.write('(');
Serial.write(currentMap->choices[currentKeyIndex]);
Serial.write(')');
}
}
else if (millis() - t0 >= 1000) {
finalKey = currentMap->choices[currentKeyIndex];
state = WAITING;
}
break;
}
return finalKey;
}
void setup() {
Serial.begin(115200);
Serial.println("Ready");
}
void loop() {
char k = getKey();
if (k != NO_KEY) {
Serial.print(F("\nGot : "));
Serial.println(k);
}
}