본문 바로가기

라즈베리파이 5

라즈베리파이 4x4 Keypad 테스트 코드 C

반응형

 

오늘은 4x4 키패드를 Raspberry Pi 4에 연결해 보겠습니다. 임베디드 프로젝트에서 키패드는 사용자 입력을 받는 데 사용됩니다. 예를 들어 계산기, ATM 키패드 등이 있습니다. 4x4, 4x3 등 다양한 유형의 키패드가 있습니다. 

 

 

 

 

 

 

 

 

 

 

#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define ROWS 4
#define COLS 4

char keys[ROWS][COLS] = {
    {'1', '2', '3', 'A'},
    {'4', '5', '6', 'B'},
    {'7', '8', '9', 'C'},
    {'*', '0', '#', 'D'}
};

// **사용자가 라즈베리파이와 키패드를 연결한 실제 wiringPi 핀 번호로 수정해야 합니다.**
// 'gpio readall' 명령으로 확인하세요.
int rowPins[ROWS] = {1, 4, 5, 6};  // 예시: R1, R2, R3, R4 핀 (INPUT)
int colPins[COLS] = {12, 3, 2, 0}; // 예시: C1, C2, C3, C4 핀 (OUTPUT)

char pressedKey = '\0'; 

void init_keypad() {
    for (int c = 0; c < COLS; c++) {
        pinMode(colPins[c], OUTPUT);
        digitalWrite(colPins[c], HIGH);
    }

    // 행 핀에 내부 풀업 저항 설정: 키 미입력 시 HIGH, 키 입력 시 LOW 감지
    for (int r = 0; r < ROWS; r++) {
        pinMode(rowPins[r], INPUT);
        pullUpDnControl(rowPins[r], PUD_UP);
    }
}

int findLowRow() {
    for (int r = 0; r < ROWS; r++) {
        if (digitalRead(rowPins[r]) == LOW) {
            return r;
        }
    }
    return -1;
}

char get_key() {
    int rowIndex;
    char currentKey = '\0';

    for (int c = 0; c < COLS; c++) {
        // 현재 열을 LOW로 설정 (활성화)
        digitalWrite(colPins[c], LOW);
        
        usleep(1000); 
        
        // 눌린 키가 있는지 확인 (LOW 신호 감지)
        rowIndex = findLowRow();
        
        if (rowIndex > -1) {
            currentKey = keys[rowIndex][c];
            
            // 디바운싱: 이미 눌려있는 키가 아닌 경우에만 처리
            if (currentKey != pressedKey) {
                pressedKey = currentKey;
                digitalWrite(colPins[c], HIGH); 
                return currentKey;
            }
            digitalWrite(colPins[c], HIGH);
            return '\0';
        }
        
        // 현재 열을 다시 HIGH로 비활성화
        digitalWrite(colPins[c], HIGH);
    }
    
    // 키 떼짐 감지 (모든 열을 스캔하여 현재 눌려있는 키가 없는지 확인)
    for (int c = 0; c < COLS; c++) {
        digitalWrite(colPins[c], LOW);
        if (findLowRow() > -1) {
            digitalWrite(colPins[c], HIGH);
            return '\0'; 
        }
        digitalWrite(colPins[c], HIGH);
    }

    if (pressedKey != '\0') {
        pressedKey = '\0';
    }

    return '\0';
}

int main(void) {
    if (wiringPiSetup() == -1) {
        return 1;
    }

    init_keypad();
    printf("Keypad test started. Press a key. (Ctrl+C to exit)\n");

    while(1) {
        char key = get_key();
        if (key != '\0') {
            printf("Key pressed: %c\n", key);
            fflush(stdout);
        }
        delay(10);
    }
    
    return 0;
}

 

 

 

반응형