---
# System prepended metadata

title: 0104 - 4x4 keypad

---

# 0104 - 4x4 keypad
```clike=
const byte KEY_COL = 4;  //const => 常數
const byte KEY_ROW = 4;
// column(行) vs row(列)

//***********************
char keymap[KEY_ROW][KEY_COL] = {
  {'1' , '2' , '3' , 'A'} ,
  {'4' , '5' , '6' , 'B'} ,
  {'7' , '8' , '9' , 'C'} ,
  {'*' , '0' , '#' , 'D'}
};

const byte COL_PINs[KEY_COL] = {9 , 8 , 7 , 6};
const byte ROW_PINs[KEY_ROW] = {13 , 12 , 11 , 10};

byte i,j;
byte scanVal; //value

void setup() {
  Serial.begin(9600);

    for(i =0; i < 4 ; i++) {
      pinMode(COL_PINs[i] , OUTPUT);
      pinMode(ROW_PINs[i] , INPUT);
      digitalWrite(COL_PINs[i], HIGH);
      digitalWrite(ROW_PINs[i], HIGH);
      //腳位是INPUT的時候 drigtalWrite 卻是HIGH 這是上拉電阻
      //因為鍵盤連線的腳位沒有接觸時，可以視為一個銅線，會接收環境的干擾訊號
      //需要「上拉電阻」阻隔訊號
    }

  

}

void loop() {

  for(i = 0; i < 4 ; i++){
    for(j = 0; j < 4 ; j++){
      digitalWrite(COL_PINs[j] , LOW);
      scanVal = digitalRead(ROW_PINs[i]);

      if(scanVal == LOW){
        Serial.println(keymap[i][j]);
        delay(200);
        digitalWrite(COL_PINs[j] , HIGH);
        break;
      }

      digitalWrite(COL_PINs[j] , HIGH);

    }
  }

}


```