#include <msp430x14x.h>
#include"1602.c"
#include"1602.h"
#define uchar unsigned char
#define uint unsigned int
uchar key_flag;
uchar key_value;
/********时钟初始化*************/
void init_clk()
{
uchar i;
BCSCTL1&=~XT2OFF; //打开XT振荡器
BCSCTL2|=SELM1+SELS+DIVS_3;//MCLK 8M and SMCLK 1M
do
{
IFG1 &= ~OFIFG; //清除振荡错误标志
for(i = 0; i < 100; i++)
_NOP(); //延时等待
}
while ((IFG1 & OFIFG) != 0); //如果标志为1继续循环等待
IFG1&=~OFIFG;
}
/*********************延时***********/
void delay(uchar k)
{
uint i,j;
for(i=0;i<k;i++)
for(j=0;j<121;j++)
;
}
/*************快速扫描**********/
void fast_scan()
{
uchar temp;
P1OUT&=0x0F;
temp=P1IN&0x0F;
if(temp==0x0F)
key_flag=0;
else key_flag=1;
}
/****************等待按键释放********/
void over()
{
uchar temp;
P1OUT&=0x0F;
while(1)
{
temp=P1IN&0x0F;
if(temp==0x0F)
break;
}
}
/****************键值程序**************/
uchar get_key()
{
uchar tmp1,tmp2,key,i,j;
P1DIR|=0xFF;
P1OUT=0xF0;//低四位输出0
P1DIR=0x0F;//高四位输入
tmp1=P1IN&0xF0;//读入高四位的值
switch(tmp1)
{
case 0xE0:i=0;break;
case 0xD0:i=1;break;
case 0xB0:i=2;break;
case 0x70:i=3;break;
default:i=4;break;
}
P1DIR=0xFF;
P1OUT=0x0F;//高四位输出0
P1DIR=0xF0;//低四位输入
tmp2=P1IN&0x0F;//读入低四位的值
switch(tmp2)
{
case 0x0E:j=0;break;
case 0x0D:j=1;break;
case 0x0B:j=2;break;
case 0x07:j=3;break;
default:j=4;break;
}
_NOP();
key=j*4+i;
return key;
}
void main( void )
{
// Stop watchdog timer to prevent time out reset
WDTCTL = WDTPW + WDTHOLD;
uchar dis[3];
P3DIR|=BIT0+BIT1+BIT2;
P4DIR=0xFF;
P1OUT=0xFF;
P1DIR=BIT4+BIT5+BIT6+BIT7;
init_clk();
init_LCD();
display("The key is: ",0,0);
while(1)
{
fast_scan();
if(key_flag==0)
continue;
key_flag=0;
delay(20);
fast_scan();
if(key_flag==1)
{
key_value=get_key();
dis[0]=key_value/10+48;
dis[1]=key_value%10+48;
dis[2]='\0';
display(dis,7,1);
P1DIR=BIT4+BIT5+BIT6+BIT7;
over();
delay(100);
}
}
}