Arduino中的键盘4x4

时间:2017-12-19 14:49:51

标签: c++ arduino keypress keypad

任何人都可以向我解释这段代码的含义是什么:

byte rowPins[numRows] = {9, 8, 7, 6}; //Rows 0 to 3
byte colPins[numCols]= {5, 4, 3, 2}; //Columns 0 to 3

他们如何获得{9, 8, 7, 6}{5, 4, 3, 2}的数量。这是完整的代码:

/*4x4 Matrix Keypad connected to Arduino
This code prints the key pressed on the keypad to the serial port*/
#include <Keypad.h>
const byte numRows= 4; //number of rows on the keypad
const byte numCols= 4; //number of columns on the keypad

//keymap defines the key pressed according to the row and columns just as appears on the keypad
char keymap[numRows][numCols]= {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

//Code that shows the the keypad connections to the arduino terminals
byte rowPins[numRows] = {9, 8, 7, 6}; //Rows 0 to 3
byte colPins[numCols]= {5, 4, 3, 2}; //Columns 0 to 3

//initializes an instance of the Keypad class
Keypad myKeypad= Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);

void setup() {
  Serial.begin(9600);
}
//If key is pressed, this key is stored in 'keypressed' variable
//If key is not equal to 'NO_KEY', then this key is printed out
//if count=17, then count is reset back to 0 (this means no key is pressed during the whole keypad scan process

void loop() {
  char keypressed = myKeypad.getKey();
  if (keypressed != NO_KEY) {
    Serial.print(keypressed);
  }
}

2 个答案:

答案 0 :(得分:0)

代码中的所有内容似乎都很容易理解。随着评论,它显然是一个水晶。但正如你所说,你需要一个解释,我会提供一个答案:

const byte numRows= 4; //number of rows on the keypad
const byte numCols= 4; //number of columns on the keypad

在上面给出的代码段中,两个字节的变量将被声明为numRowsnumCols,并使用值4进行初始化。

byte rowPins[numRows] = {9, 8, 7, 6}; //Rows 0 to 3
byte colPins[numCols]= {5, 4, 3, 2}; //Columns 0 to 3

所以这是你坚持的代码。两个字节数组将被声明为rowPinscolPins,每个都是4(因为numRowsnumCols的值是4)。其范围为0到3(如c或java中的数组)。在这个数字中,9,8,7,6将被分配给数组rowPins,而5,4,3,2将被分配给数组colPins。现在这些价值将如何或在何处。它们将以从索引0到索引3的顺序方式存储。即

rowPins[0]=9
rowPins[1]=8
rowPins[2]=7
rowPins[3]=6
colPins[0]=5
colPins[1]=4
colPins[2]=3
colPins[3]=2

这就是他们获得这些数字的方式。

答案 1 :(得分:0)

他们没有得到分配给arduino引脚2,3,4,5,6,7,8,9的数字

byte rowPins[numRows] = {9, 8, 7, 6}; //Rows 0 to 3
byte colPins[numCols]= {5, 4, 3, 2}; //Columns 0 to 3

您也可以使用4,5,6,7,8,9,10,11引脚。只需检查要为行和列输入分配的引脚,然后根据其编写代码即可。