在定時器中斷函數里執行獨立按鍵的掃描程序


/*
  上一例在主函數中利用累計定時器中斷的次數來實現獨立按鍵的檢測,但是
 如果在某些項目中,需要主函數里面間歇性地執行一些一氣呵成的耗時任務,
 當主函數正在執行一氣呵成的耗時任務時(前提沒有關閉定時器中斷),這個時候
 如果有按鍵按下來,就有可能沒有被及時響應而遺漏了。
  解決辦法:在定時器里面處理獨立按鍵的掃描程序,可以避免上述問題。
*/
#include "REG52.H"
#define const_voice_short 40
#define const_voice_long 200
#define const_key_time1 20
#define const_key_time2 20
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 int uiKeyTimeCnt2=0;
unsigned char ucKeyLock2=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;
 }
 else if(ucKeyLock1==0)
 {
  uiKeyTimeCnt1++;
  if(uiKeyTimeCnt1>const_key_time1)
  {
   uiKeyTimeCnt1=0;
   ucKeyLock1=1;
   ucKeySec=1;
  }   
 }
 if(key_sr2==1)
 {
  ucKeyLock2=0;
  uiKeyTimeCnt2=0;
 }
 else if(ucKeyLock2==0)
 {
  uiKeyTimeCnt2++;
  if(uiKeyTimeCnt2>const_key_time2)
  {
   uiKeyTimeCnt2=0;
   ucKeyLock2=1;
   ucKeySec=2;
  }
 }
}
void key_service()
{
 switch(ucKeySec)
 {
  case 1:
   uiVoiceCnt=const_voice_short;
   ucKeySec=0;
   break;
   
  case 2:
   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