본문 바로가기

메이킹/아두이노

4x4 키패드 활용하기

반응형

키패드는 여러 개의 스위치들이 반복적으로 나열된 것으로 전자식 잠금장치, 통신장치 등에 많이 사용되며 단자의 개수는 행(row)과 열(column)의 합이 됩니다.

여기서는 4×4 키패드를 사용하므로 단자의 개수는 4+4=8이 됩니다. 두이노와 키패드의 단자는 1:1로 연결하면 되는데 아래의 회로도를 참고하여 연결하시면 됩니다.

키패드의 종류
4x4 키패드

 

 

1) 키패드 번호 출력하기

 

회로도

 

 

 

 

 

라이브러리 설치하기

  • 아두이노 메뉴: 스케치 > 라이브러리 포함하기 > 라이브러리 관리…

 

 

 

 

 

소스코드

#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'*','0','#','D'},
  {'7','8','9','C'},
  {'4','5','6','B'},
  {'1','2','3','A'}
};
byte rowPins[ROWS] = {4,5,6,7}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8,9,10,11}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); 

void setup(){
  Serial.begin(9600);
}
  
void loop(){
  char customKey = customKeypad.getKey();
  
  if (customKey){
    Serial.println(customKey);
  }
}

 

 

2) 키패드 도어락 만들기

 

회로도

 

 

 

 

소스코드

#include <Keypad.h>
#include <Servo.h>

int pwd_ok=0;
int count=0;
char PWD[4]={'1','0','0','4'}; //본인 비밀번호


const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'*','0','#','D'},
  {'7','8','9','C'},
  {'4','5','6','B'},
  {'1','2','3','A'}
};
byte rowPins[ROWS] = {4,5,6,7}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8,9,10,11}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); 
Servo myservo;

void setup(){
  Serial.begin(9600);
  myservo.attach(12);
}
  
void loop(){
  char myKey = customKeypad.getKey();
 
  if (myKey){
    Serial.print(myKey); 
    
    if(myKey==PWD[count]){
      count++;
      pwd_ok++;
      //Serial.println(myKey);   
    }
    else if(myKey!=PWD[count]){
      count++;
    }

    if (myKey=='#'){
      pwd_ok=0;
      count=0;
      Serial.println(" Password Reset");
    }

    if(count==4){
      if(pwd_ok==4){
        myservo.write(180);
        Serial.println(" Open the door");
      }
      else{
        myservo.write(0);
        Serial.println(" Close the door");        
      }
      pwd_ok=0;
      count=0;
      }
    }
}

 

반응형