STC单片机按键扫描程序演示




/*
 *AVR scan Keybord demo
 *------------------------
 *DESIGNED:yingxian_Fei
 *2012-2-25
 *This demo code use for show the action after someone pressed the keybord.
 *The program show the action to user by light LED.
 */
#include
#include
#include
#include


#define POUT P0   //设置输出的P口
#define MASK 0xff
#define LEDCON 0x03




sfr AUXR   = 0x8E;


sbit KEY1 = P2^0;
sbit KEY2 = P2^1;
sbit KEY3 = P2^2;
sbit KEY4 = P2^3;


void AppCall(void);
void Task1(void);
void Task2(void);
void Task3(void);
void Task4(void);
void InitMCU(void);
void InitTimer0(void);
void KeyBord(void);
void Delay_ms(unsigned char ms);


unsigned char S1,S2,S3,S4;


int main(void)
{
   InitMCU();
   while(1)  {
      AppCall();
   }
   return 0;
}


void AppCall(void)
{
   if(S1 == 1&&S2 != 1&&S3 != 1&&S4 != 1)  {
      Task1();
   }
   if(S2 == 1&&S1 != 1&&S3 != 1&&S4 != 1)  {
      Task2();
   }
   if(S3 == 1&&S2 != 1&&S1 != 1&&S4 != 1)  {
      Task3();
   }
   if(S4 == 1&&S2 != 1&&S3 != 1&&S1 != 1)  {
      Task4();
   }
}


void Task1(void)
{
   unsigned char temp;
   POUT = MASK; 
   temp = _crol_(LEDCON,0);
   POUT = ~temp;
}




void Task2(void)
{
   unsigned char temp;
   POUT = MASK; 
   temp = _crol_(LEDCON,2);
   POUT = ~temp;
}


 
void Task3(void)
{
   unsigned char temp;
   POUT = MASK; 
   temp = _crol_(LEDCON,4);
   POUT = ~temp;
}


 
void Task4(void)
{
   unsigned char temp;
   temp = _crol_(LEDCON,6);
   POUT = ~temp;
}


void InitMCU(void)
{
    AUXR = AUXR|0x80;  // T0, 1T Mode
    InitTimer0();   
}


void InitTimer0(void)
{
    TMOD = 0x01;
    TH0 = 0x0F7; //200us
    TL0 = 0x5C;
    EA = 1;
    ET0 = 1;
    TR0 = 1;
}


void Timer0Interrupt(void) interrupt 1
{
    TF0 = 0;
TH0 = 0x0F7;
    TL0 = 0x5C;
    KeyBord();
TR0 = 1;
}


void KeyBord(void)
{
   if(KEY1 == 0)  {
      Delay_ms(1);
 if(KEY1 == 0)  {
    S1 = 1;
S2 = S3 = S4 = 0;
 }
   }
   if(KEY2 == 0)  {
      Delay_ms(1);
 if(KEY2 == 0)  {
    S1 = S3 = S4 = 0;
S2 = 1;
 }
   }
   if(KEY3 == 0)  {
      Delay_ms(1);
 if(KEY3 == 0)  {
    S1 = S2 = S4 = 0;
S3 = 1;
 }
   }
   if(KEY4 == 0)  {
      Delay_ms(1);
 if(KEY4 == 0)  {
    S1 = S2 = S3 = 0;
S4 = 1;
 }
   }
}


void Delay_ms(unsigned char ms)
{
   unsigned char a,b;
   while(ms--)  {
     for(b=18;b>0;b--)  {
        for(a=152;a>0;a--);
            _nop_();
}
   }
}




编者寄语:此小演示程序仅用于演示按键扫描程序的设计。单片机为STC12C5A60S2,晶振频率为11.0592M。单片机P口上接8个LED灯。在按下按钮后分别点亮几个LED灯用于模拟其各自任务。按键采用查询方式。按键防抖动时间为1ms。使用时可通过宏定义PCONFIG设置输出所用的P口,如果不设置则采用默认输出P0口做为信号输出。闲暇至于写下此小程序仅供娱乐,大家多多指教。

你可能感兴趣的:(单片机)