时间:2024.8.30
作者:Whappy
目的:手撕51(第二遍)
代码:
main.c
#include <REGX52.H>
#include "LCD1602.h"
#include "Delay.h"
#include "MatrixKey.h"
unsigned char KeyNum;
void main()
{
LCD_Init();
//LCD_ShowString(1,2,"Hello World");
while(1)
{
KeyNum = MatrixKey();
if(KeyNum)
{
LCD_ShowNum(1,1,KeyNum,2);
}
}
}
MatrixKey.c
#include <REGX52.H>
#include "Delay.h"
unsigned char MatrixKey()
{
unsigned char KeyNumber = 0;
/***************************************
软件按键消抖
如果P1_7按下则延时20ms,用while(P1_7 == 0);检测一下P1_7 == 0确实按下了,接下来手松开再延时20ms
***************************************/
//第1列扫描
P1 = 0XFF; //所有的管脚置1
P1_3 = 0; //第一列置0,准备检测通过P1_7 - P1_4给低电平检测按键是否按下
if(P1_7 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 1;
}
if(P1_6 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 5;
}
if(P1_5 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 9;
}
if(P1_4 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 13;
}
//第2列扫描
P1 = 0XFF; //所有的管脚置1
P1_2 = 0;
if(P1_7 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 2;
}
if(P1_6 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 6;
}
if(P1_5 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber =10;
}
if(P1_4 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 14;
}
//第3列扫描
P1 = 0XFF; //所有的管脚置1
P1_1 = 0;
if(P1_7 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 3;
}
if(P1_6 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 7;
}
if(P1_5 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 11;
}
if(P1_4 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 15;
}
//第4列扫描
P1 = 0XFF; //所有的管脚置1
P1_0 = 0;
if(P1_7 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 4;
}
if(P1_6 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 8;
}
if(P1_5 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 12;
}
if(P1_4 == 0)
{
Delay(20);
while(P1_7 == 0);
Delay(20);
KeyNumber = 16;
}
return KeyNumber;
}
Matrix.h
#ifndef __MATRIXKEY_H__
#define __MATRIXKEY_H__
unsigned char MatrixKey();
#endif