Some simple Arduino code to read from a keypad
Wired up a cheap keypad to an Arduino. These keypads were a few cents each on ebay and look suitable for a project I’m working on. This is the same keypad as used here and their code is worth referring to.
The following reads presses from the keypad and prints them over serial. It only returns a valid keypress when a different key is pressed, not when the key is held down.
#define rows 4 #define cols 4 const char keymap[rows][cols] = { { 1, 2, 3, 10 } , { 4, 5, 6, 11 } , { 7, 8, 9, 12 } , {13, 0,14, 15 } }; const int row_pins[rows] = { 2, 3, 4, 5 }; const int col_pins[cols] = { 6, 7, 8, 9 }; void setup() { Serial.begin(9600); for (int r=0;r<rows;r++) { pinMode(row_pins[r],INPUT); digitalWrite(row_pins[r],HIGH); } for (int c=0;c<cols;c++) { pinMode(col_pins[c],OUTPUT); digitalWrite(col_pins[c],HIGH); } } int get_key() { int key=-1; for(int c=0;c<cols;c++) { digitalWrite(col_pins[c],LOW); for(int r=0;r<rows;r++) { if(digitalRead(row_pins[r]) == LOW) { key = keymap[r][c]; digitalWrite(col_pins[c],HIGH); return key; } } digitalWrite(col_pins[c],HIGH); } return key; } int last_key=0; int get_key_db() { int k1 = get_key(); delay(10); int k2 = get_key(); if((k1 == k2) && (k2 != last_key)) {last_key=k2; return k2;} else return -1; } void loop() { int key = get_key_db(); if(key != -1) { Serial.print("key: "); Serial.print(key); Serial.print("\n"); } }