51单片机程序框架之单击与双击

/******************************************************************************
此程序是依据吴坚鸿程序框架,在普中51 A2单片机开发板上的程序练习
程序目标:按键单击与双击,单击LED取反,双击按下LED1取反
*******************************************************************************/
#include<REG51.H>
#define Main_Fosc 12000000L //默认系统时钟12Mhz
#define T1MS  (65536-Main_Fosc/12/1000)  //12分频下1ms定时器的装载值,n=t/T=t/(12/f)=0.001*f/12=f/12/1000
#define Key_Debounce 40  //按键debounce time
#define Key_DK_Debounce 300  //双击的间隔时间
sbit LED=P2^0;
sbit LED1=P2^1;
sbit Key=P3^1;
unsigned char Key_Handle=0;  //按键值,没有按下时,默认为0,单击为1,双击为2
void Sys_Init();    //系统初始化
void Delay_Long();   //长延时,等待系统稳定
void Perpherial_Init();  //端口初始化
void Key_Scan();  //按键扫描函数
void Key_Service(); //按键响应函数

void main()
{
    Sys_Init(); 
    Delay_Long();
    Perpherial_Init();
    while (1)
    {
        Key_Service();
    }
    
}

void Sys_Init()
{
    TMOD=0X01; //定时器0模式1
    TL0=T1MS;
    TH0=T1MS>>8;
}

void Delay_Long()
{
    unsigned char i,j;
    for(i=0;i++;i<220)
    {
        for(j=0;j<220;j++)
        ;
    }
}

void Perpherial_Init()
{
    ET0=1;
    TR0=1;
    EA=1;
}

void Timer0_ISR() interrupt 1   //定时器0中断函数
{
	TL0=T1MS;
    TH0=T1MS>>8;
    Key_Scan();
}

void Key_Scan()
{
    static unsigned int Key_CNT;
    static unsigned char Key_Lock;
    static unsigned int Key_DK_CNT;
    static unsigned char Key_Press_CNT;

    if (0!=Key)
    {
       Key_CNT=0;
       Key_Lock=0;
       if (Key_Press_CNT>=1)
       {
        Key_DK_CNT++;
        if (Key_DK_CNT>Key_DK_Debounce)
        {
            Key_Press_CNT=0;
            Key_DK_CNT=0;
            Key_Handle=1;
        }
        
       }   
    }
    else if (0==Key_Lock)
    {
        Key_CNT++;
        if (Key_CNT>Key_Debounce)
        {
            Key_Lock=1;
            Key_DK_CNT=0;
            Key_Press_CNT++;
           if (Key_Press_CNT>=2)
            {
                Key_Press_CNT=0;
                Key_Handle=2;
            }
            
            
        }
        
    }
        
}

void Key_Service()
{
    if (0==Key_Handle)
    {
        return;
    }
    
    switch (Key_Handle)
    {
    case 1:
        LED=!LED;
        Key_Handle=0;
        break;
    case 2:
        LED1=!LED1;
        Key_Handle=0;
        break;
    }
    
}
posted @ 2024-05-04 22:56  硬软  阅读(348)  评论(0)    收藏  举报