以前用延时消抖,比较浪费时间,现在用状态机设计,不占用太多时间,但是需要一个定时器。
1.状态机按键消抖
*****************************************************************
//状态机按键消抖
//CPU:mega32
//编译器:winavr
#include <avr/io.h>
#include <avr/interrupt.h>
char key_scan(void); #define PRESS ( PIND&(1<<3) ) == 0
#define NOT_PRESS ( PIND&(1<<3) ) != 0 int main(void)
{
DDRC |= (1 << 7);//PC7置为输出
PORTD |= 1<<3;//按键上拉 TIMSK |= 1<<OCIE0;//不屏蔽T0匹配中断
OCR0 = 0X10;//匹配值 大约10ms
TCCR0 |= (1 << WGM01) | (0 << WGM00) | (1 << CS02) | (0 << CS01) | (1 << CS00);//CTC模式,1024分频
sei();//使能全局中断
while(1);
} SIGNAL(SIG_OUTPUT_COMPARE0)//TIMER0 匹配中断服务程序
{
if ( key_scan() == 1 )
PORTC ^= 1<<7;//PC7取反
} char key_scan(void)
{
static char state=0;
switch(state)
{
case 0: if ( PRESS )
{
state = 1;
return 0;
}
else
{
state = 0;
return 0;
} case 1: if ( PRESS )
{
state = 2;
return 1;
}
else
{
state = 0;
return 0;
} case 2: if ( PRESS )
{
state = 2;
return 0;
}
else
{
state = 0;
return 0;
}
}
return 0;
}
******************************************************************
2.状态机按键检测连击
*****************************************************************
//状态机按键消抖
//CPU:mega32
//编译器:winavr
#include <avr/io.h>
#include <avr/interrupt.h> char key_scan(void); #define PRESS ( PIND&(1<<3) ) == 0
#define NOT_PRESS ( PIND&(1<<3) ) != 0 int main(void)
{
DDRC |= (1 << 7) | (1 << 6);//PC7 PC6 置为输出
PORTD |= 1<<3;//PD3按键内部上拉 TIMSK |= 1<<OCIE0;//不屏蔽T0匹配中断
OCR0 = 0X10;//匹配值 大约10ms
TCCR0 |= (1 << WGM01) | (0 << WGM00) | (1 << CS02) | (0 << CS01) | (1 << CS00);//CTC模式,1024分频
sei();//使能全局中断
while(1);
} SIGNAL(SIG_OUTPUT_COMPARE0)//TIMER0 匹配中断服务程序
{
char key;
key = key_scan();
if ( key == 1 )
PORTC ^= 1<<7;//PC7取反
if ( key == 2 ) //连击
PORTC ^= 1<<6;//PC6取反
} char key_scan(void)
{
static char state=0;
char times;
switch(state)
{
case 0: if ( PRESS )
{
state = 1;
return 0;
}
else
{
state = 0;
return 0;
} case 1: if ( PRESS )
{
times = 0;
state = 2;
return 1;
}
else
{
state = 0;
return 0;
} case 2: if ( PRESS )
{
state = 2;
times++;
if (times > 50)//500ms
{
times = 0;
return 2;
}
else
return 0;
}
else
{
state = 0;
return 0;
}
}
return 0;
}
******************************************************************
|