原创 51单片机开发板键盘扫描程序

2009-6-22 11:04 2957 5 5 分类: MCU/ 嵌入式
//-----------------------函数声明,变量定义--------------------------------------------------------
#include <reg51.h>
sbit LED_1 =P1^4;
sbit LED_2 =P1^5;
sbit LED_3 =P1^6;
sbit LED_4 =P1^7;
#define KEY P2

unsigned char scan_key();              //扫描键盘,返回键值(高四位代表行,低四位代表列)
void delay(unsigned int N);

//-----------------------变量声明---------------------------------------------------------------------

  main()
 {
 int ge=0,j=0,shi=0,bai=0,qian=0,key_value,key_flag,key_flash_num;//key_value为获取的键值,keyu_flag为按键标志,key_flash_num用于闪烁
 char leddisplay[]={0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90};
 while(1)
  {
    key_value=scan_key();
    if (key_value==0x18)//铵1键时
       { 
   key_flag=1;//表示1键按下,进入闪烁状态
key_flash_num=0;//准备闪烁
  }
    if (key_value==0x28)//按2键时
  key_flag=0;//表示2键,退出闪烁状态

    if (key_flag==0)//正掌显示0000-5959
{
     if (j==100)//j用于控制变化的频率
   {
ge++;
if(ge==10)
       {
ge=0;
           shi++;
if(shi==6)
           {
shi=0;
bai++;
if (bai==10)
   {
bai=0;
qian++;
if (qian==6)
   {
ge=0;
shi=0;
bai=0;
qian=0;
}
}
}
}
j=0;
}
 j++;
}

   if (key_flag==0)//正常显示
   {
     LED_1=0;
     P0=leddisplay[ge];
delay(100);
     LED_1=1;
   }
   else 
   {
     if (key_flash_num==8)//闪烁处理,8表用于加强闪烁的频率
   {
         LED_1=0;
         P0=leddisplay[ge];
    delay(100);
         LED_1=1;
key_flash_num=0;
}
   }

     key_flash_num++;

LED_2=0;
     P0=leddisplay[shi];
delay(100);
     LED_2=1;
   
     LED_3=0;
     P0=leddisplay[bai];
delay(100);
     LED_3=1;

     LED_4=0;
     P0=leddisplay[qian];
delay(100);
     LED_4=1;
   }
 }
/*A---88H  3---48H  2---28H  1---18H
  B---84H  6---44H  5---24H  4---14H
  C---82H  9---42H  8---22H  7---12H
  D---81H  E---41H  0---21H  F---11H
  */
//--------------------------------------------------------------------------------------------------
// 函数名称: scan_key
// 函数功能: //扫描键盘,返回键值(高四位代表行,低四位代表列)
//--------------------------------------------------------------------------------------------------
unsigned char scan_key()              //扫描键盘,返回键值(高四位代表行,低四位代表列)
  {
   unsigned char scancode,keycode;
   scancode=0xef;                    //键盘扫描码,采用逐行扫描的方法
   while(scancode!=0xff)
   {
    KEY=scancode;                      //输入扫描码,扫描P2.4对应的行
    keycode=KEY;                       //读出数据,看是否在此行上的某列键盘被按下   
    if((keycode&0x0f)!=0x0f)   
    break;                             //扫描到按下的键,则退出  
    scancode=(keycode<<1)|0x0f;        //否则,更新扫描码继续扫描  
   }  
   keycode=~keycode; 
   return(keycode);
   }

void delay(unsigned int N)
 {
  int i;
  for (i=0;i<N;i++);
 }


PARTNER CONTENT

文章评论0条评论)

登录后参与讨论
我要评论
0
5
关闭 站长推荐上一条 /3 下一条