AdSense

Tuesday 13 January 2015

Arduino - read keypad

(Deutsche Version) Today I want to explain how to read out a simple keypad with an Arduino, as seen in the following image. You could use this keypad from ebay: Keypad.
The keypad has 8 pins. 4 in each case are for the rows respectively the columns. A pressed key connects two of these pins. 4 pins are used as an output on the Arduino, the other 4 pins as an input. I used pin 22, 24, 26 and 28 as output and 30, 32, 34, 36 as input so you can easily attach the keypad to the Arduino using a pin header.
Now a voltage is applied to one output after the other and the input pins are measured whether they receive this voltage. This shows directly which key was pressed. My code reads the pressed keys and sends them via the serial bus to the computer as soon as a key state has changed.

//For different sizes of Keypads, you can adjust the numbers here. Important: Also change the keyValues array!
const int numOuts = 4;
const int numIns = 4;
//These are the 4 output pins, adjust it if you use a different pin mapping
int outs[numOuts] = {22, 24, 26, 28};
//These are the 4 input pins, adjust it if you use a different pin mapping
int ins[numIns] = {30, 32, 34, 36};
//This array contains the values printed to the different keys
char keyValues[numOuts][numIns] = {{'1','2','3','A'},{'4','5','6','B'},{'7','8','9','C'},{'*','0','#','D'}};
//This array contains whether a pin is pressed or not
boolean pressed[numOuts][numIns];

void setup() {  
  Serial.begin(9600);
  //Define all outputs and set them to high
  for (int i = 0; i < numOuts; i++)
  {
    pinMode(outs[i], OUTPUT);
    digitalWrite(outs[i], HIGH);
  }
  //Define all inputs and activate the internal pullup resistor
  for (int i = 0; i < numIns; i++)
  {
    pinMode(ins[i], INPUT);
    digitalWrite(ins[i], HIGH);
  }
}

//Read whether a key is pressed
void KeyPressed()
{
  for (int i = 0; i < numOuts; i++)
  {
    //Activate (set to LOW) one output after another
    digitalWrite(outs[i], LOW);
    //Wait a short time
    delay(10);
    for (int j = 0; j < numIns; j++)
    {
      //Now read every input and invert it (HIGH = key not pressed (internal pullup), LOW = key pressed (because the output was set to LOW)
      boolean val = !digitalRead(ins[j]);
      //If the value changed, send via serial to the computer and save the value in the "pressed" array
      if (pressed[i][j] != val)
      {
        char str[255];
        sprintf(str, "%c pressed: %d", keyValues[i][j], val);
        Serial.println(str);
        pressed[i][j] = val;
      }
      
    }
    //Deactivate (set back to HIGH) the output
    digitalWrite(outs[i], HIGH);
  }
}

//Yeah, do this forever...
void loop()
{
  KeyPressed();
}

No comments:

Post a Comment