#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar one;
uchar two=8;
uchar k;
sbit rs=P2^0;
sbit e=P2^1;
sbit scl=P2^4;
sbit sda=P2^5;
sbit led=P2^7;
uchar code table1[]="Your password...";
uchar code table2[]="error !!!";
uchar code table3[]="unlock ok";
uchar code key1[]={0xfe,0xfd,0xfb};
uchar code key2[]={0xee,0xde,0xbe,0x7e,0xed,0xdd,0xbd,0x7d,0xeb,0xdb};
uchar code key3[]={0xbb,0x7b};
uchar code key4[]="0123456789";
void delay_1us()
{;;} //微秒延時
void delay(uchar time) //毫秒延時
{
uchar i;
for(;time>0;time--)
for(i=0;i<125;i++);
}
void write_com(uchar com) //液晶命令輸入
{
rs=0;
P1=com;
delay(1);
e=1;
delay(1);
e=0;
}
void write_dat(uchar datt) //液晶數據輸入
{
rs=1;
P1=datt;
delay(1);
e=1;
delay(1);
e=0;
}
void init() //液晶初始化
{
e=0;
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
}
void display1(uchar * dat,uchar n,uchar m) table1,table2,table3數據的輸入
{
uchar i;
write_com(0x80+m+1);
for(i=0;i<n;i++)
{
write_dat(dat[i]);
delay(1);
}
}
void inti1() //I2c的初始化
{
scl=1;
delay_1us();
sda=1;
delay_1us();
}
void start() //I2c的開啟
{
sda=1;
delay_1us();
scl=1;
delay_1us();
sda=0;
delay_1us();
}
void repons() //I2c的應答
{
uchar i;
scl=1;
delay_1us();
while((sda==1)&&(i<250))
i++;
scl=0;
delay_1us();
}
void stop() //I2c的停止
{
sda=0;
delay_1us();
scl=1;
delay_1us();
sda=1;
delay_1us();
}
void writebyte(uchar //I2c的寫入一字節
{
uchar i,temp;
temp=dat;
for(i=0;i<8;i++)
{
temp=temp<<1;
scl=0;
delay_1us();
sda=CY;
delay_1us();
scl=1;
delay_1us();
}
scl=0;
delay_1us();
sda=1;
delay_1us();
}
uchar readbyte() //I2c的讀一字節
{
uchar i,d;
scl=0;
delay_1us();
sda=1;
for(i=0;i<8;i++)
{
scl=1;
delay_1us();
d=(d<<1)|sda;
scl=0;
delay_1us();
}
return d;
}
void write_dat1(uchar address, uchar dat) //寫入數據
{
start();
writebyte(0xa0);
repons();
writebyte(address);
repons();
writebyte(dat);
repons();
stop();
}
uchar read_dat1(uchar address) //讀數據
{
uchar dat;
start();
writebyte(0xa0);
repons();
writebyte(address);
repons();
start();
writebyte(0xa1);
repons();
dat=readbyte();
stop();
return dat;
}
uchar compare() //比較輸入的密碼與存入的密碼
{
uchar i,n,m,b=0;
for(i=0;i<6;i++)
{
n=read_dat1(1+i);
m=read_dat1(8+i);
if(n==m) b++;
}
if(b==6) return 1;
else return 0;
}
void key_buf() //密碼的輸入
{
uchar i,j,uu;
for(i=0;i<3;i++)
{
P3=key1[i];
uu=P3;
if((uu&0xf0)!=0xf0)
{
delay(10);
for(j=0;j<10;j++)
{
if(key2[j]==uu)
if(k<6)
{
write_dat(key4
[j]); //輸入6位數密碼
write_dat1(two,j);
two++;
k++;
}
while(P3==key2[j]);
}
if(uu==key3[1]) //開密碼
{
one=compare();
if(one==1)
{
led=0;
display1
(table3,9,0x40);
}
else display1(table2,9,0x40);
one=0;
while(P3==key3[1]);
}
if(uu==key3[0]) //鎖密碼
{
k=0;
two=8;
led=1;
write_com(0x01);
display1(table1,15,0x40);
write_com(0x80+0x40+1);
while(P3==key3[0]);
}
}
}
}
void main()
{
uchar i;
init();
inti1();
display1(table1,15,0x40);
write_com(0x80+0x40+1);
for(i=0;i<6;i++)
write_dat1(i+1,i+1); //初始密碼123456
while(1)
{
key_buf();
}
} |