# 03按键

• 一、IO口输入内容
• 二、什么是按键
• 三、按键分析
• 1.独立按键
• 2.矩阵按键
• 3.抖动
• 四、按键案例
• 1.按下按键点亮一个LED灯
• 2.按键模拟二进制
• 3.矩形按键控制LED灯的亮灭
• 总结

# 一、IO口输入内容

51单片机的输入电平是非常简单的，不需要像stm32一样，需要调节端口的模式才能读取端口的电平，51单片机只需要读取端口的电平就可以了，非常的简单。

``````int main(){
int a = P2_2;
}
``````

# 三、按键分析

## 1.独立按键

``````void main(){
char a = P3_0;
if (a == 0){
;//执行的内容
}
}
``````

## 2.矩阵按键

``````void main(){
char row, col; //定义两个变量来接收端口输入
P1 = 0x0F;
col = P1;
P1 = 0xF0;
row = P1;
}
``````

``````char btnNumber[] = {0x77, 0x7B, 0x7D, 0x7E, 0xB7, 0xBB, 0xBD, 0xBE, 0xD7, 0xDB, 0xDD, 0xDE, 0xE7, 0xEB, 0xED, 0xEE};
``````

``````void main(){
char btnNumber[] = {0x77, 0x7B, 0x7D, 0x7E, 0xB7, 0xBB, 0xBD, 0xBE, 0xD7, 0xDB, 0xDD, 0xDE, 0xE7, 0xEB, 0xED, 0xEE};
char row, col, i; //定义两个变量来接收端口输入
P1 = 0x0F;
col = P1;
P1 = 0xF0;
row = P1;
for (i = 0; i < 16; i++){
if (col + row == btnNumber[i]){
;
}
}
}
``````

``````void main(){
char btnNumber[] = {0x77, 0x7B, 0x7D, 0x7E, 0xB7, 0xBB, 0xBD, 0xBE, 0xD7, 0xDB, 0xDD, 0xDE, 0xE7, 0xEB, 0xED, 0xEE};
char row, col, i; //定义两个变量来接收端口输入
P1 = 0x0F;
col = P1;
P1 = 0xF0;
row = P1;
if (col + row == btnNumber[1]){
;
}
else if (col + row == btnNumber[2]){
;
}
else if (col + row == btnNumber[0]){
;
}
}
``````

## 3.抖动

``````void delay(unsigned int time){
unsigned char i, j;
while(time--){
i = 15;
j = 90;
do
{
while (--j);
} while (--i);
}
}
void main(){
delay(10);
char a = P3_0;
if (a == 0){
;//执行的内容
}
}
``````

# 四、按键案例

## 1.按下按键点亮一个LED灯

``````#include <at89x51.h>
void delay(unsigned int time){
unsigned char i, j;
while(time--){
i = 15;
j = 90;
do
{
while (--j);
} while (--i);
}
}
void main(){
char row;
while(1){
delay(15);
row = P3_1;
while (row == 0){
P2_2 = 0;
}
}
}
``````

``````#include <at89x51.h>
void delay(unsigned int time){
unsigned char i, j;
while(time--){
i = 15;
j = 90;
do
{
while (--j);
} while (--i);
}
}
void main(){
char row, x = 0;
while(1){
row = P3_1;
delay(15);
if (row == 0){
P2_2 = ~P2_2;
delay(15);
}
}
}
``````

## 2.按键模拟二进制

``````#include <at89x51.h>
void delay(unsigned int time){
unsigned char i, j;
while(time--){
i = 15;
j = 90;
do
{
while (--j);
} while (--i);
}
}
void main(){
char row, x = 0;
while(1){
row = P3_1;
delay(15);
if (row == 0){
x++;
delay(15);
}
P2 = ~x;
}
}
``````

## 3.矩形按键控制LED灯的亮灭

``````#include <at89x51.h>
char btnNumber[] = {0x77, 0x7B, 0x7D, 0x7E, 0xB7, 0xBB, 0xBD, 0xBE, 0xD7, 0xDB, 0xDD, 0xDE, 0xE7, 0xEB, 0xED, 0xEE};
void delay(unsigned int time){
unsigned char i, j;
while(time--){
i = 15;
j = 90;
do
{
while (--j);
} while (--i);
}
}
void main(){
char row, col, x = 0;
while(1){
P1 = 0x0F;
col = P1;
P1 = 0xF0;
row = P1;
delay(10);
if (col + row == btnNumber[0]){
P2_0 = ~P2_0;
delay(10);
}
else if (col + row == btnNumber[1]){
P2_1 = ~P2_1;
delay(10);
}
}
}
``````