Advertisement
dragonflydiy

Arduino code for a 4x3 keypad

Jan 22nd, 2016
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.68 KB | None | 0 0
  1. // matrix keypad reader demo
  2. // John Ridley 2015-03-09
  3. // published on DragonflyDIY.com as part of the Arduino Blocks project
  4. // released CC0 public domain dedication
  5.  
  6. int col1 = 4;
  7. int col2 = 3;
  8. int col3 = 2;
  9. int row1 = 8;
  10. int row2 = 7;
  11. int row3 = 6;
  12. int row4 = 5;
  13.  
  14. void setup()
  15. {
  16.    Serial.begin(9600);
  17. }
  18.  
  19. void loop()
  20. {
  21.   char lastkey = 0;
  22.  
  23.   while (1)
  24.   {
  25.     char curkey = readkey();
  26.     if (curkey != lastkey)
  27.     {
  28.       if (curkey != 0)
  29.       {
  30.         Serial.println(curkey);
  31.       }
  32.       lastkey = curkey;
  33.     }
  34.     delay(10); // debouncing
  35.   }
  36. }
  37.  
  38. char readkey()
  39. {
  40.   int rows[4] = {row1, row2, row3, row4};
  41.   int cols[4] = {col1, col2, col3};
  42.   char chars[4][3] = {{'1','2','3'},{'4','5','6'},{'7','8','9'},{'*','0','#'}};
  43.  
  44.   // set EVERYTHING to input - we only want to DRIVE one row at a time (either high OR low)
  45.   // turn on pull-up resistors on the columns
  46.   pinMode(col1, INPUT_PULLUP);
  47.   pinMode(col2, INPUT_PULLUP);
  48.   pinMode(col3, INPUT_PULLUP);
  49.  
  50.   // reset all rows to input to start with
  51.   for (int currow = 0; currow < 4; currow++)
  52.   {
  53.     pinMode(rows[currow], INPUT);
  54.   }
  55.  
  56.   for (int currow = 0; currow < 4; currow++)
  57.   {
  58.     // turn this row to output and drive it low
  59.     pinMode(rows[currow], OUTPUT);
  60.     digitalWrite(rows[currow], 0);
  61.    
  62.     // scan all the columns, look for a low.  If it's low it must be because
  63.     // the button is being pressed (since we have the pull-ups activated on the columns)
  64.     for (int curcol = 0; curcol < 3; curcol++)
  65.     {
  66.       int val = digitalRead(cols[curcol]);
  67.       if (val == 0)
  68.         return chars[currow][curcol];
  69.     }
  70.     pinMode(rows[currow], INPUT);
  71.   }
  72.   return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement