51单片机 05 矩阵键盘

嘻嘻,LCD在RC板子上可以勉强装上,会有一点歪。

一、矩阵键盘

在键盘中按键数量较多时,为了减少I/O口的占用,通常将按键排列成矩阵形式;采用逐行或逐列的“扫描”,就可以读出任何位置按键的状态。(IO口默认高电平1)

51单片机 05 矩阵键盘_第1张图片51单片机 05 矩阵键盘_第2张图片

代码在文件夹中。我改了LCD代码的延时问题。

MatrixKey.c代码

#include 
#include "Delay.h"

unsigned char MatrixKey()
{
	// 按列扫描
	unsigned char KeyNumber=0;
	P1=0xFF;
	P13=0x00;
	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=0x00;
	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=0x00;
	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=0x00;
	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 
#include "Delay.h"
#include "LCD1602.h"

unsigned char KeyNum;

void main()
{
	LCD_Init();
	LCD_ShowString(1,1,"HelloRain");
    while(1)
	{
		KeyNum=MatrixKey();
		if(KeyNum) LCD_ShowNum(2,1,KeyNum,2);
	}
}

二、矩阵键盘密码锁

main.c

#include 
#include "Delay.h"
#include "LCD1602.h"
#include "MatrixKey.h"

unsigned char KeyNum;
unsigned int password,count;

void main()
{
	LCD_Init();
	LCD_ShowString(1,1,"PassWord:");
    while(1)
	{
		KeyNum=MatrixKey();
		if(KeyNum) 
		{
			if(KeyNum<=10) //s1-s10按下,输入密码 
			{
				if(count<4)
				{
					password*=10; //密码左移
					password+=KeyNum%10; 
					count++;
					LCD_ShowNum(2,1,password,4);
				}
				
			}
			else if(KeyNum==11) 
			{
				if(password==2345)
				{
					LCD_ShowString(1,14,"OK ");
					password=0;
					count=0;
					LCD_ShowNum(2,1,password,4);
				}
				else 
				{
					LCD_ShowString(1,14,"ERR");
					password=0;
					count=0;
					LCD_ShowNum(2,1,password,4);
				}
			}
			else if(KeyNum==12)
			{
				password=0;
				count=0;
				LCD_ShowNum(2,1,password,4);
			}
		}
	
	}
}

你可能感兴趣的:(51单片机,计算机外设,嵌入式硬件)