键盘也是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秒数量级之间,而单片机处理键盘的时间小于一个毫秒,因此单片机可以迅速的一行一行或者一列一列的读取键盘信号,用快速的处理来让人感觉不到延迟。这样也节约了数字输入口。
- 序言
- 第一章 arduino简介和学习
- 第一节 arduino介绍
- 第二节 学习方法概述
- 第三节 计算机的智能
- 第二章 开始学习之旅
- 第一节 安装环境和购买硬件的说明
- 第二节 介绍一个具体的范例
- 第三章 分类官网教程讲解
- 第一节 Basics类的示例项目
- 第二节 数字端口的示例
- 第三节 模拟端口的示例
- 第四节 串口通信的示例
- 第五节 LED显示的示例
- 第六节 arduino处理矩阵键盘
- 第七节 LCD显示范例
- 第四章 综合实践项目制作教程
- 第一节 简单的计算器
- 第五章 复习题
- 单选题
- 编程题目
- 单选题答案
- 编程题答案
- 第1题
- 第2题
- 第3题
- 第4题
- 第5题
- 第6题
- 第7题
- 第8题
- 第9题
- 第10题
- 第11题
- 第12题
- 第13题
- 第14题
- 第15题
- 第16题
- 第17题
- 复习题包含翻译
- 第六章 快速复习
- 第一节 英文解说