原创 51单片机扫描键盘程序2

2009-6-22 11:08 3296 3 3 分类: 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;
 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;
key_flash_num=0;
  }

    if (key_value==0x28)//按下2键
   key_flag=0;

    if (key_value==0x48&&key_flag==1)//按下3键,3键的功能,用于增加闪烁位的值
  {
    ge++;
if (ge==10)
    ge=0;
       }
    if (key_value==0x14&&key_flag==1)//按下4键,4键的功能,用于减小闪烁位的值
  {
    ge--;
if (ge==0)
    ge=0;
       }


    if (key_flag==0)
{
     if (j==100)
   {
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)
   {
         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,keycode_nd;
   scancode=0xef;                    //键盘扫描码,采用逐行扫描的方法
   while(scancode!=0xff)
   {
    KEY=scancode;                      //输入扫描码,扫描P2.4对应的行
    keycode=KEY;                       //读出数据,看是否在此行上的某列键盘被按下   
    if((keycode&0x0f)!=0x0f)  
 {
       while (((keycode_nd=KEY)&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
3
关闭 站长推荐上一条 /3 下一条