AdSense

Dienstag, 13. Januar 2015

Arduino - Keypad auslesen

(English version) Heute möchte ich kurz vorstellen wie man ein simples Keypad, wie im folgenden Bild zu sehen, mit dem Arduino auslesen kann. Man könnte dazu z.B. dieses hier von ebay nehmen: Keypad.
Das Keypad hat 8 Anschlüsse. Jeweils 4 sind dabei für die Zeilen bzw. Spalten. Ein Tastendruck verbindet nun zwei dieser Anschlüsse. 4 Anschlüsse werden am Arduino als Output genutzt, die anderen 4 als Input. Ich habe Pin 22, 24, 26 und 28 als Output benutzt und 30, 32, 34, 36 als Input, man kann das Display dadurch sehr einfach anschließen, indem man eine Stiftleiste benutzt.
Nun legt man nacheinander an jeden Output eine Spannung an und misst dabei, welcher Input diese Spannung abbekommt. Dadurch weiß man sofort welche Tasten gedrückt wurden. Mein Code liest die Tasten aus und sendet, sobald sich der Status einer Taste geändert hat, dies über die serielle Schnittstelle an den Computer.


//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();
}

Keine Kommentare:

Kommentar veröffentlichen