记录并分享 矩阵键盘制作密码盘并数码管显示
效果:没输入时:
密码正确时
密码错误时
说明:
1. 上电时,数码管显示下划线"_ _ _ _ _"
2. 矩阵键盘依次输入5个数,会实时显示在数码管上
3. 按确认时,如果密码正确,数码管最后一位显示"1",否则显示"0"
4. 按取消时,恢复到"_ _ _ _ _"
代码:
<Digital.c>
#include <REGX51.H>
#include "Delay.h"
unsigned char* ten2bin(unsigned char num){
unsigned char binarr = {0,0,0};
unsigned char index;
for(index=0;num>0;index++){
binarr = num % 2;
num = num / 2;
}
return binarr;
}
void Digital_init(){
P2_2 = 1;
P2_3 = 1;
P2_4 = 1;
P0 = 0x00;
}
void showDigital(unsigned char locate,signed char num){
unsigned char *bin,locate_index;
unsigned char numArr[] = {0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
locate_index = 8-locate;
bin = ten2bin(locate_index);
P2_2 = bin;
P2_3 = bin;
P2_4 = bin;
P0 = numArr;
if(num==-1){
P0 = 0x08;
}
Delay(2);
P0 = 0x00; //消影
}
<matrixKey.c>
#include <REGX51.H>
#include <INTRINS.H>
#include "Delay.h"
unsigned char pressKey(){
signed char key = -1;
P1 = 0xFF;
P1_3 = 0;
if(P1_7==0){
Delay(20);
while(P1_7==0){}
Delay(20);
key = 1;
}
if(P1_6==0){
Delay(20);
while(P1_6==0){}
Delay(20);
key = 5;
}
if(P1_5==0){
Delay(20);
while(P1_6==0){}
Delay(20);
key = 9;
}
P1 = 0xFF;
P1_2 = 0;
if(P1_7==0){
Delay(20);
while(P1_7==0){}
Delay(20);
key = 2;
}
if(P1_6==0){
Delay(20);
while(P1_6==0){}
Delay(20);
key = 6;
}
if(P1_5==0){
Delay(20);
while(P1_6==0){}
Delay(20);
key = 0;
}
P1 = 0xFF;
P1_1 = 0;
if(P1_7==0){
Delay(20);
while(P1_7==0){}
Delay(20);
key = 3;
}
if(P1_6==0){
Delay(20);
while(P1_6==0){}
Delay(20);
key = 7;
}
if(P1_5==0){
Delay(20);
while(P1_6==0){}
Delay(20);
key = 11;
}
P1 = 0xFF;
P1_0 = 0;
if(P1_7==0){
Delay(20);
while(P1_7==0){}
Delay(20);
key = 4;
}
if(P1_6==0){
Delay(20);
while(P1_6==0){}
Delay(20);
key = 8;
}
if(P1_5==0){
Delay(20);
while(P1_6==0){}
Delay(20);
key = 12;
}
return key;
}
<Delay.c>
void Delay(unsigned char ms){//@12.000MHz
unsigned char data i, j;
while(ms--){
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
}
}
<main.c>
#include <REGX51.H>
#include "matrixKey.h"
#include "Digital.h"
void main()
{
signed char keyNum;
signed char password = {-1,-1,-1,-1,-1},i = 0,index = 0;
unsigned char corret_password = {1,2,3,4,5};
unsigned char is_corret = -1;
Digital_init();
while(1){
while(1){
keyNum = pressKey();
if(keyNum != -1){
if(i<5){
password = keyNum;
i++;
}
}
if(keyNum == 11){
//按"确认"
is_corret = 1;
for(index=0;index<5;index++){
if(password != corret_password){
//密码错误
is_corret = 0;
}
}
}
if(keyNum == 12){
//按"取消"
i = 0;
is_corret = -1;
for(index = 0;index<5;index++){
password = -1;
}
}
for(index = 0;index<5;index++){
showDigital(index+1,password);
}
if(is_corret != -1){
showDigital(8,is_corret);
}
}
}
}
页:
[1]