单片机——矩阵键盘

该程序的功能是驱动矩阵键盘,并且可以通过数码管显示出所按键的逻辑值
#include
#include "./delay/delay.h"
#define SEGPORT P0
#define KEYPORT P1
unsigned char bitdata[2] = {0xfe,0xfd};
unsigned char segdata[16] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
unsigned char disdata[2] = {0x3f,0x3f};
sbit seg_sel = P2^1;
sbit bit_sel = P2^0;
void display()
{
   static unsigned char i = 0;
 
   SEGPORT = 0x0;
   seg_sel = 1;
   seg_sel = 0;
 
   SEGPORT = 0xff;
   bit_sel = 1;
   bit_sel = 0;
 
   SEGPORT = disdata[i];
   seg_sel = 1;
   seg_sel = 0;
 
   SEGPORT = bitdata[i];
   bit_sel = 1;
   bit_sel = 0;
 
   i++;
   if(i == 2)
  {
     i = 0;
  }
 
}
void timer0_init(void)
{
   EA = 1;
   TH0 = (65536 - 2000)/256;
   TL0 = (65536 - 2000)%256;
   TMOD |= 0x01;
   TR0 = 1;
   ET0 = 1;
}
void timer0_isr(void) interrupt 1
{
   TH0 = (65536 - 2000)/256;
   TL0 = (65536 - 2000)%256;
 
   display();
}
unsigned char key_scan(void)
{
   unsigned char keyvalue;
  
   KEYPORT = 0xf0;
 
   if(0xf0 != KEYPORT)
  {
     KEYPORT = 0xfe;
     if(0xfe != KEYPORT)
    {
       keyvalue = KEYPORT;
       keyvalue &= 0xf0;
       keyvalue += 0x0e;
       while(0xfe != KEYPORT);
          delay_ms(10);
      while(0xfe != KEYPORT);
     
       return keyvalue;
    }
    KEYPORT = 0xfd;
    if(0xfd != KEYPORT)
    {
       keyvalue = KEYPORT;
       keyvalue &= 0xf0;
       keyvalue += 0x0d;
       while(0xfd != KEYPORT);
          delay_ms(10);
      while(0xfd != KEYPORT);
     
       return keyvalue;
    }
    KEYPORT = 0xfb;
    if(0xfb != KEYPORT)
    {
       keyvalue = KEYPORT;
       keyvalue &= 0xf0;
       keyvalue += 0x0b;
       while(0xfb != KEYPORT);
          delay_ms(10);
      while(0xfb != KEYPORT);
     
       return keyvalue;
    }
    KEYPORT = 0xf7;
    if(0xf7 != KEYPORT)
    {
       keyvalue = KEYPORT;
       keyvalue &= 0xf0;
       keyvalue += 0x07;
       while(0xf7 != KEYPORT);
          delay_ms(10);
      while(0xf7 != KEYPORT);
     
       return keyvalue;
    }
    return 0xff;
  }
}
unsigned char key()
{
   unsigned char num;
   //unsigned char i = 0;
   num = key_scan();
 
   switch(num)
   {
     case 0x7e: return 1;break;
     case 0xbe: return 2;break;
     case 0xde: return 3;break;
     case 0xee: return 4;break;
     case 0x7d: return 5; break;
     case 0xbd: return 6;break;
     case 0xdd: return 7;break;
     case 0xed: return 8;break;
     case 0x7b: return 9;break;
     case 0xbb: return 10;break;
     case 0xdb: return 11;break;
     case 0xeb: return 12;break;
     case 0x77: return 13; break;
     case 0xb7: return 14;break;
     case 0xd7: return 15;break;
     case 0xe7: return 16;break;
     default: return  0xff; break;
    }
}
void main()
{
   unsigned char keyvalue;
   timer0_init();
   while(1)
  {
      
     keyvalue = key();
    
     if(0xff != keyvalue)
    {
         disdata[0] = segdata[keyvalue / 10];
         disdata[1] = segdata[keyvalue % 10];
    }
  }
}

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