🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
键盘也是arduino或者单片机最为常用的器件之一,是一种方便的人机接口供用户输入一定的信息。而键盘的接法和上一节讲到的矩阵LED类似,需要一定的编程技巧,否则会占用大量的数字端口或者不够。 ![](https://img.kancloud.cn/29/3e/293e53b7c2577ee7bb6e110b18bdf8e7_698x421.png) ![](https://img.kancloud.cn/e9/08/e9083ef6ddaabda3f5bbbd60d8ae45c6_489x441.png) ``` const byte ROWS = 4; //four rows const byte COLS = 3; //four columns //define the cymbols on the buttons of the keypads char hexaKeys[ROWS][COLS] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'}, {'#','0','*'} }; byte rowPins[ROWS] = { 5, 4, 3, 2}; //connect to the row pinouts of the keypad byte colPins[COLS] = { 6, 7, 8}; //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); for (int c=0;c<4;c++) { pinMode(rowPins[c], INPUT_PULLUP); } for (int c=0;c<3;c++) { pinMode(colPins[c],OUTPUT); } } char getKey() { byte input,KeyPressRow=100,KeyPressCol=100; for (int c=0;c<3;c++) { digitalWrite(colPins[c],LOW); } for (int c=0;c<4;c++) { input=digitalRead(rowPins[c]); if(input==LOW) { KeyPressRow=c; break; } } digitalWrite(colPins[0],LOW); digitalWrite(colPins[1],HIGH); digitalWrite(colPins[2],HIGH); input=digitalRead(rowPins[KeyPressRow]); if(input==LOW) KeyPressCol=0; digitalWrite(colPins[0],HIGH); digitalWrite(colPins[1],LOW); digitalWrite(colPins[2],HIGH); input=digitalRead(rowPins[KeyPressRow]); if(input==LOW) KeyPressCol=1; digitalWrite(colPins[0],HIGH); digitalWrite(colPins[1],HIGH); digitalWrite(colPins[2],LOW); input=digitalRead(rowPins[KeyPressRow]); if(input==LOW) KeyPressCol=2; if((KeyPressRow!=100) and (KeyPressCol!=100)) return(hexaKeys[KeyPressRow][KeyPressCol]); else return 0; } void loop(){ char customKey = getKey(); if (customKey){ Serial.println(customKey); delay(200); } } ``` 编程思路也和以前的矩阵LED一样,利用计算机非常快速的处理能力,实现了对键盘的行扫描或者列扫描。人类触摸键盘的时间在0.1秒数量级之间,而单片机处理键盘的时间小于一个毫秒,因此单片机可以迅速的一行一行或者一列一列的读取键盘信号,用快速的处理来让人感觉不到延迟。这样也节约了数字输入口。