电子密码锁
#include
#include
#include
#define uchar unsigned char
#define uint unsigned int
#define Delay4us() {_nop_();_nop_(); _nop_();_nop_();}
***it SCL =P3^2;
***it SDA =P3^3;
//上次按键和当前按键序号,该矩阵中序号范围0-15,16表示无按键
uchar Pre_KeyNo = 16,KeyNo = 16;
uchar code title_Test[] ="Your Password..."; //标题字符串
uchar DSY_BUFFER[10] =""; //显示缓冲
uchar UserPassword[10] =""; //用户输入的密码
void LCD_Init(); //液晶初始化
void Display_String(uchar *str,uchar LineNo); //液晶指定行显示字符串
void IIC_24C04_Init(); //IIC初始化
void Beep(); //蜂鸣器
uchar RecString(uchar Slave,uchar Subaddr,uchar *Buffer,uchar N); //从IIC读取数据
uchar SendString(uchar Slave,uchar Subaddr,uchar *Buffer,uchar N); //向IIC写入数据
uchar Keys_Scan(); //键盘扫描,返回键盘号0-15
***it LED_OPEN =P2^7; //开锁亮灯
***it BEEP=P3^7;
***it LCD_RS= P2^0;
***it LCD_RW= P2^1;
***it LCD_EN= P2^2;
//起始位//
void Start()
{
SDA = 1;
SCL = 1;
Delay4us();
SDA = 0;
Delay4us();
SCL = 0;
}
//停止位//
void Stop()
{
SDA = 0;
SCL = 1;
Delay4us();
SDA = 1;
Delay4us();
SCL = 0;
}
//IIC总线初始化//
void IIC_24C04_Init()
{
SCL = 0; Stop();
}
//发送应答信号//
void ACK()
{
SDA = 0; SCL = 1; Delay4us(); SCL = 0; SDA = 1;
}
//发送非应答信号//
void NO_ACK()
{
SDA = 1; SCL = 1; Delay4us(); SCL = 0; SDA = 0;
}
//从芯片读取1字节//
uchar RecByte()
{
uchar i,rd;
rd = 0x00;
SDA = 1;
for(i = 0; i<8; i++)
{
SCL = 1; rd <<=1; rd|= SDA; Delay4us(); SCL = 0; Delay4us();
}
SCL = 0;
Delay4us();
return rd;
}
//向芯片发送1字节//
uchar SendByte(uchar wd)
{
uchar i;
bit ack0;
for(i = 0; i<8; i++)
{
SDA = (bit)(wd & 0x80 );
_nop_(); _nop_(); SCL = 1; Delay4us(); SCL = 1; wd <<= 1;
}
Delay4us();
SDA = 1;
SCL = 1;
Delay4us();
ack0 = !SDA;
SCL = 0;
Delay4us();
return ack0;
}
//发送多字节数据函数//
uchar SendString(uchar Slave,uchar Subaddr,uchar *Buffer,uchar N)
{
uchar i;
Start();
if(!SendByte(Slave)) return 0;
if(!SendByte(Subaddr)) return 0;
for(i = 0; i
{
if (!SendByte(Buffer)) return 0;
}
Stop();
return 1;
}
//接收多字节数据函数//
uchar RecString(uchar Slave,uchar Subaddr,uchar *Buffer,uchar N)
{
uchar i;
Start();
if(!SendByte(Slave)) return 0;
if(!SendByte(Subaddr)) return 0;
Start();
if(!SendByte(Slave + 1)) return 0;
for(i = 0; i
{
Buffer = RecByte();
ACK();
}
Buffer[N-1] = RecByte();
NO_ACK();
Stop();
return 1;
}
void DelayMS(uint x);
uchar Keys_Scan()
{
uchar Tmp,KeyNo = 0;
P1 = 0x0F;
DelayMS(1);
Tmp = P1^ 0x0F;
switch(Tmp)
{
case 1: KeyNo = 0;break;
case 2: KeyNo = 1;break;
case 4: KeyNo = 2;break;
case 8: KeyNo = 3;break;
default: KeyNo = 16;
}
P1 = 0xF0;
DelayMS(1);
Tmp = P1 >> 4^ 0x0F;
switch(Tmp)
{
case 1: KeyNo += 0;break;
case 2: KeyNo += 4;break;
case 4: KeyNo += 8;break;
case 8: KeyNo += 12;
}
return KeyNo;
}
//延时//
void DelayMS(uint x)
{
uchar i;
while (x--) for (i=0;i<120;i++);
}
//蜂鸣器子程序//
void Beep()
{
uchar i;
for(i = 0;i<100;i++)
{
DelayMS(1);
BEEP= ~BEEP;
}
BEEP =0;
}
//清除密码//
void Clear_Password()
{
UserPassword[0]='