【51单片机】矩阵键盘

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
强下拉,弱上拉。

在这里插入图片描述
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);
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值