专注电子技术学习与研究
当前位置:单片机教程网 >> MCU设计实例 >> 浏览文章

一个改进型的4*4矩阵键盘扫描----用了SWITCH CASE 嵌套之后程序循序简洁了好多

作者:李俊轩   来源:本站原创   点击数:  更新时间:2013年07月18日   【字体:

#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar temp,num,bai,shi,ge;
uchar key[]={0x3f,0x5f,0x6f};
uchar code table[]=
{
0x3f , 0x06 , 0x5b ,
0x4f , 0x66 , 0x6d ,
0x7d , 0x07 , 0x7f ,
0x6f };
void keyscan();
void delay(uchar z);
void dsp(uchar bai,uchar shi,uchar ge);
void main()

 while(1)
 {
    keyscan(); 
    dsp(bai,shi,ge);
 }
}
void delay(uchar z)
{
 uchar x,y;
 for(x=100;x--;x>0)
  for(y=z;y--;y>0);
}
void dsp(uchar bai,uchar shi,uchar ge)
{
  
   bai=num/100;
   shi=num%100/10;
   ge=num%10;
   
   P0=0xfb;
   P2=table[bai];
   delay(1);
   P0=0xfd;
   P2=table[shi];
   delay(1);
   P0=0xfe;
   P2=table[ge];
   delay(1);
}
void keyscan()
{   uchar i;
 for(i=0;i<3;i++)
   {
     P1=key[i];
     temp=P1;
     temp&=0x0f;
     if(temp!=0x0f) //如果有键按下
     {
      delay(5);
   temp=P1;
      temp&=0x0f;
   if(temp!=0x0f)//确实有键按下
    {
     switch(temp)
     {
      case 0x07:switch(i)
          {
            case 0:num=1;break;
            case 1:num=5;break;
            case 2:num=9;break;
          };
      
      break;
 
      case 0x0b:switch(i)
          {
            case 0:num=2;break;
            case 1:num=6;break;
            case 2:num=10;break;
          };
      break;
 
      case 0x0d:switch(i)
          {
            case 0:num=3;break;
            case 1:num=7;break;
            case 2:num=11;break;
          };
      break;
 
      case 0x0e:switch(i)
          {
            case 0:num=4;break;
            case 1:num=8;break;
            case 2:num=12;break;
          };;
      break;
 
      while(temp!=0xf0) //松开手后就跳出循环,否则等待松手
      {
      temp=P1;
      temp=temp&0xf0;
      dsp(bai,shi,ge);
      }
     }
        
    }
     }
   }
}  

关闭窗口

相关文章