Go Down

Topic: Simple Keypad code (Read 220 times) previous topic - next topic


I didn't feel like learning the built in keypad library so I made a function to get what key was pressed.

It's made for 4x4 keypads but can be modified for other sizes.

It uses pins 2,3,4,5 for the rows and pins 6,7,8,9 for the columns. You might have to adjust accordingly depending on you're keypad.

It starts at zero instead of one, and returns the number of the key that was pressed. If nothing was pressed then -1 is returned.
As far as I know, this code is protected against short circuts

Code: [Select]
int GetKey()
  //Arduino UNO
  //Made for a 4x4 keypad
  //Output pins should be the rows
  //Output pins are set as pinMode(INPUT) when not beaing checked. This is to protect against short   //circuts if 2 buttons are pressed at
  //at the same time

  //Keys start at 0, not 1 (Zero indexed)

  //Input pins are pulled up through the internal pullup, thus he output pins output low

  int outPins[] = {2, 3, 4, 5};
  int inPins[] = {6, 7, 8, 9};

  int keyPressed;

  //Set input pins to high to activate internal pullup
  for (int p  = 6; p <= 9; p++)
    pinMode(p, INPUT_PULLUP);

  //Loop through each row and column
  for (int op = 2; op <= 5; op++)
    pinMode(op, OUTPUT);
    digitalWrite(op, LOW);

    for (int ip = 6; ip <= 9; ip++)
      if (digitalRead(ip) == LOW)
        //Key pressed is = (row number * 4) + column number
        //Subtract two to get the row number and subtract 6 to get the column number
        keyPressed = ( (op - 2) * 4) + (ip - 6);
        pinMode(op, INPUT);
        return keyPressed;
    //digitalWrite(op, LOW);
    pinMode(op, INPUT);

  return -1;

Go Up