#include "io430.h"
#include "intrinsics.h"
#include "io430g2232.h"
#define uint unsigned int
#define uchar unsigned char
#define N_key 0 //无键
#define S_key 1 //单键
#define L_key 3 //长键
#define key_state_0 0
#define key_state_1 1
#define key_state_2 2
#define key_state_3 3
uchar time_10ms_ok=0;
uint wADC;
uchar key=0;
void Delay_Nms(uint k)
{
uint h,s;
for(h = k;h > 0;h--)
for(s = 1000;s > 0;s--)
__no_operation(); //delay
}
/*=============
低层按键(I/0)扫描函数,即低层按键设备驱动,只返回无键、短按和长按.
===============*/
unsigned char key_driver()
{
static unsigned char key_state = key_state_0, key_time = 0;
unsigned char key_press, key_return = N_key;
key_press = (P1IN&BIT2); // 读按键I/O电平
switch (key_state)
{
case key_state_0: // 按键初始态
if (!key_press)
key_state = key_state_1; // 键被按下状态转换到按键消抖和确认状态
break;
case key_state_1: // 按键消抖与确认态
if (!key_press)
{
key_time = 0;
key_state = key_state_2; // 按键仍然处于按下,消抖完成,状态转换到按下键时间的计
} // 时状态,但返回的还是无键事件
else
key_state = key_state_0; // 按键已抬起,转换到按键初始态。此处完成和实现软件消
break; // 抖,其实按键的按下和释放都在此消抖的。
case key_state_2:
if(key_press==BIT3)
{
key_return = S_key; // 此时按键释放,说明是产生一次短操作,回送S_key
key_state = key_state_0; // 转换到按键初始态
}
else if (++key_time >= 100) // 继续按下,计时加20ms(20ms为本函数循环执行间隔)
{
key_return = L_key; // 按下时间>1000ms,此按键为长按操作,返回长键事件
key_state = key_state_3; // 转换到等待按键释放状态
}
break;
case key_state_3: // 等待按键释放状态,此状态只返回无按键事件
if (key_press==BIT3) key_state = key_state_0; //按键已释放,转换到按键初始态
break;
}
return key_return;
}
//TIMER0_A0 interrupt service routine
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A (void)
{
time_10ms_ok = 1;
}
void main(void)
{
WDTCTL = WDTPW + WDTHOLD;
BCSCTL1= CALBC1_1MHZ;
DCOCTL = CALDCO_1MHZ;
P1DIR |= BIT1; //P1.1=Output
P2DIR |= BIT6+BIT7; //P2.6 /2.7 =Output
P1REN |= BIT2; //Set pull-up resistor
TACCTL0 = CCIE; // CCR0 interrupt enabled
TACCR0 =20000; // about 20ms
TACTL = TASSEL_2+MC_1+TACLR; //TACLK=SMCLK=1M,UP Mode,At CCR0 then clear to 0
__bis_SR_register(LPM0_bits+GIE);
while(1)
{
if (time_10ms_ok) //每10ms执行一次,
{
time_10ms_ok =0;
key = key_driver();
if (key == L_key)
{
P1OUT |= BIT1;
P2OUT = 0;
}
else if(key == S_key)
{
P2OUT |= BIT7;
P1OUT =0;
P2OUT &= ~BIT7;
}
else
{
P1OUT =0;
P2OUT =0;
}
}
}
} |