强下拉,弱上拉。
MatrixKey.h
#ifndef __MATRIXKEY_H__
#define __MATRIXKEY_H__
unsigned char MatrixKey();
#endif
MatrixKey.c
#include <STC89C5xRC.H>
#include "Delay.h"
//判断对应按键被按下
unsigned char MatrixKey(){
unsigned char KeyNumber = 0;
P1 = 0xFF;
P13 = 0;
if(P17 == 0){Delay(20);while(P17 == 0);Delay(20);KeyNumber = 1;}
if(P16 == 0){Delay(20);while(P16 == 0);Delay(20);KeyNumber = 5;}
if(P15 == 0){Delay(20);while(P15 == 0);Delay(20);KeyNumber = 9;}
if(P14 == 0){Delay(20);while(P14 == 0);Delay(20);KeyNumber = 13;}
P1 = 0xFF;
P12 = 0;
if(P17 == 0){Delay(20);while(P17 == 0);Delay(20);KeyNumber = 2;}
if(P16 == 0){Delay(20);while(P16 == 0);Delay(20);KeyNumber = 6;}
if(P15 == 0){Delay(20);while(P15 == 0);Delay(20);KeyNumber = 10;}
if(P14 == 0){Delay(20);while(P14 == 0);Delay(20);KeyNumber = 14;}
P1 = 0xFF;
P11 = 0;
if(P17 == 0){Delay(20);while(P17 == 0);Delay(20);KeyNumber = 3;}
if(P16 == 0){Delay(20);while(P16 == 0);Delay(20);KeyNumber = 7;}
if(P15 == 0){Delay(20);while(P15 == 0);Delay(20);KeyNumber = 11;}
if(P14 == 0){Delay(20);while(P14 == 0);Delay(20);KeyNumber = 15;}
P1 = 0xFF;
P10 = 0;
if(P17 == 0){Delay(20);while(P17 == 0);Delay(20);KeyNumber = 4;}
if(P16 == 0){Delay(20);while(P16 == 0);Delay(20);KeyNumber = 8;}
if(P15 == 0){Delay(20);while(P15 == 0);Delay(20);KeyNumber = 12;}
if(P14 == 0){Delay(20);while(P14 == 0);Delay(20);KeyNumber = 16;}
return KeyNumber;
}
main.c
#include <STC89C5xRC.H>
#include "Delay.h"
#include "LCD1602.h"
#include "MatrixKey.h"
unsigned char KeyNum;
void main(){
LCD_Init();
LCD_ShowString(1,1,"I Love You!");
while(1){
KeyNum = MatrixKey();
if(KeyNum){ //若有按键按下
LCD_ShowNum(2,1,KeyNum,2);
}
}
}
实现的功能:按对应的矩阵按键,显示对应的数字。
密码锁
#include <STC89C5xRC.H>
#include "Delay.h"
#include "LCD1602.h"
#include "MatrixKey.h"
unsigned char KeyNum;
unsigned int result;
void main(){
LCD_Init();
LCD_ShowString(1,1,"PassWord");
result = 0;
LCD_ShowNum(2,1,result,4);
while(1){
KeyNum = MatrixKey();
if(KeyNum){ //若有按键按下
if(KeyNum <= 10){
result = 10 * result + ( KeyNum % 10 );
}
if(KeyNum == 11){
if(result == 1234)
LCD_ShowString(1,10,"Right!");
else
LCD_ShowString(1,10,"Wrong!");
result = 0;
}
if(KeyNum == 12){
result /= 10;
}
LCD_ShowNum(2,1,result,4);
}
}
}