Keypad

Ligação de um Arduino a este teclado da IteadStudio:

Do pino 1 ao pino 4 do teclado são as linhas, do 5 ao 8 são as colunas 

Liguei os 8 pinos do teclado a 8 resistência de 1K e aos pinos do Arduino:

*Linhas do teclado 1/2/3/4 ligam-se aos pinos do Arduino 8/7/6/5

*Colunas do teclado 5/6/7/8 ligam-se aos pinos do Arduino 12/11/10/9

Como código podemos testar o seguinte que nos diz a tecla carregada:

#include <Keypad.h>

const byte ROWS = 4; //four rows

const byte COLS = 4; //three columns

char keys[ROWS][COLS] = {

  {'1','2','3','A'},

  {'4','5','6','B'},

  {'7','8','9','C'},

  {'*','0','#','D'}

};

byte rowPins[ROWS] = {8, 7, 6, 5}; //connect to the row pinouts of the keypad

byte colPins[COLS] = {12, 11, 10, 9}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){

  Serial.begin(9600);

}

void loop(){

  char key = keypad.getKey();

  if (key != NO_KEY){

    Serial.println(key);

  }

 }

//http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1252347604/all

Temos de fazer o download e instalar a biblioteca "Keypad"

Podemos também adicionar a possibilidade de criar uma password e validar a mesma, para isso adicionamos a biblioteca "Password":

//ORIGINAL SAMPLE: http://forum.bildr.org/viewtopic.php?f=29&t=388&start=0

#include <Password.h> //http://www.arduino.cc/playground/uploads/Code/Password.zip

#include <Keypad.h> //http://www.arduino.cc/playground/uploads/Code/Keypad.zip

int Ledpin=13;

Password password = Password( "1234" );

const byte ROWS = 4; // Four rows

const byte COLS = 4; // columns

// Define the Keymap

char keys[ROWS][COLS] = {

  {'1','2','3','A'},

  {'4','5','6','B'},

  {'7','8','9','C'},

  {'*','0','#','D'}

};

// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.

byte rowPins[ROWS] = {8, 7, 6, 5}; //connect to the row pinouts of the keypad

byte colPins[COLS] = {12, 11, 10, 9}; //connect to the column pinouts of the keypad

// Create the Keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){

Serial.begin(9600);

pinMode(Ledpin, OUTPUT);

keypad.addEventListener(keypadEvent); //add an event listener for this keypad

}

void loop(){

keypad.getKey();

}

//take care of some special events

void keypadEvent(KeypadEvent eKey){

switch (keypad.getState()){

case PRESSED:

  Serial.print("Pressed: ");

  Serial.println(eKey);

  switch (eKey){

   case '*': checkPassword(); break;

   case '#': password.reset(); break;

   default: password.append(eKey);

}

}

}

void checkPassword(){

if (password.evaluate()){

   Serial.println("Success");

   //Add code to run if it works

   digitalWrite(Ledpin, HIGH);

   delay(500);

   digitalWrite(Ledpin, LOW);

}else{

   Serial.println("Wrong");

   //add code to run if it did not work

   digitalWrite(Ledpin, HIGH);

   delay(500);

  digitalWrite(Ledpin, LOW);

}

}