同一個按鍵短按與長按的區別觸發


 

#include "REG52.H"
#define const_voice_short 20  //蜂鳴器短叫的持續時間
#define const_voice_long 140  //蜂鳴器長叫的持續時間
#define const_key_time1_short1 20 //短按的按鍵去抖動延時時間
#define const_key_time_long1 400 //長按的按鍵去抖動延時時間
#define const_key_time1_short2 20
#define const_key_time_long2 400
void initial_myself();
void initial_peripheral();
void delay_long(unsigned int uiDelayLong);
void T0_time();
void key_service();
void key_scan();
sbit key_sr1=P0^0;
sbit key_sr2=P0^1;
sbit key_gnd_dr=P0^4;
sbit beep_dr=P1^5;
unsigned char ucKeySec=0;
unsigned int uiKeyTimeCnt1=0;  //按鍵去抖動延時計數器
unsigned char ucKeyLock1=0;   //按鍵觸發后自鎖的變量標志
unsigned char ucShortTouchFlag1=0; //短按的觸發標志
unsigned int uiKeyTimeCnt2=0;
unsigned char ucKeyLock2=0;
unsigned char ucShortTouchFlag2=0;
unsigned int uiVoiceCnt=0;   //蜂鳴器鳴叫的持續時間計數器
void main()
{
 initial_myself();
 delay_long(100);
 initial_peripheral();
 while(1)
 {
  key_service();
 }
}
void key_scan()  //按鍵掃描函數,放在定時中斷里
{
 if(key_sr1==1)
 {
  ucKeyLock1=0;
  uiKeyTimeCnt1=0;
  if(ucShortTouchFlag1==1) //短按觸發標志
  {
   ucShortTouchFlag1=0;
   ucKeySec=1;    //觸發一號鍵的短按
  }
 }
 else if(ucKeyLock1==0)  //有按鍵按下,且第一次被按下
 {
  uiKeyTimeCnt1++;
  if(uiKeyTimeCnt1>const_key_time1_short1)
   ucShortTouchFlag1=1; //激活按鍵短按的有效標志
  if(uiKeyTimeCnt1>const_key_time_long1)
  {
   ucShortTouchFlag1=0; //清除按鍵短按的有效標志
   uiKeyTimeCnt1=0;
   ucKeyLock1=1;   //自鎖按鍵置位,避免一直觸發
   ucKeySec=2;    //觸發1號鍵的長按
  } 
  
 }
 if(key_sr2==1)
 {
  ucKeyLock2=0;
  uiKeyTimeCnt2=0;
  if(ucShortTouchFlag2==1)
  {
   ucShortTouchFlag2=0;
   ucKeySec=3;    //觸發2號按鍵的短按
  }
 }
 else if(ucKeyLock2==0)
 {
  uiKeyTimeCnt2++;   //累加定時中斷次數
  if(uiKeyTimeCnt2>const_key_time1_short2)
   ucShortTouchFlag2=1;
  if(uiKeyTimeCnt2>const_key_time_long2)
  {
   ucShortTouchFlag2=0;
   uiKeyTimeCnt2=0;
   ucKeyLock2=1;
   ucKeySec=4;
  }
 }
}
void key_service()
{
 switch(ucKeySec)
 {
  case 1:
   uiVoiceCnt=const_voice_short;
   ucKeySec=0;
   break;
  case 2:
   uiVoiceCnt=const_voice_long;
   ucKeySec=0;
   break;
  case 3:
   uiVoiceCnt=const_voice_short;
   ucKeySec=0;
   break;
  case 4:
   uiVoiceCnt=const_voice_long;
   ucKeySec=0;
   break;
 }
}
void T0_time() interrupt 1
{
 TF0=0;
 TR0=0;
 key_scan();
 if(uiVoiceCnt!=0)
 {
  uiVoiceCnt--;
  beep_dr=0;
 }
 else
 {
  ;
  beep_dr=1;
 }
 TH0=0xf8;
 TL0=0x2f;
 TR0=1;
}
void delay_long(unsigned int uiDelayLong)
{
 unsigned int i;
 unsigned int j;
 for(i=0;i<uiDelayLong;i++)
  for(j=0;j<500;j++)
   ;
}
void initial_myself()
{
 key_gnd_dr=0;
 beep_dr=1;
 TMOD=0x01;
 TH0=0xf8;
 TL0=0x2f;
}
void initial_peripheral()
{
 EA=1;
 ET0=1;
 TR0=1;
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM