專注電子技術(shù)學(xué)習(xí)與研究
當前位置:單片機教程網(wǎng) >> MCU設(shè)計實例 >> 瀏覽文章

51單片機矩陣鍵盤例程

作者:佚名   來源:本站原創(chuàng)   點擊數(shù):  更新時間:2013年10月21日   【字體:

#include <reg52.h>

code unsigned char table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};    //表:共陽數(shù)碼管 0-9

#define DAT P1     /按鍵值數(shù)據(jù)口

sbit key0=P1^0;
sbit key1=P1^1;
sbit key2=P1^2;
sbit key3=P1^3;
sbit key4=P1^4;
sbit key5=P1^5;
sbit key6=P1^6;
sbit key7=P1^7;


#define DATA_number P2   //數(shù)碼管數(shù)據(jù)口

//-------數(shù)碼管位選------
sbit H1=P2^0;
sbit H2=P2^1;
sbit H3=P2^2;
sbit H4=P2^3;
 
sbit DA=P2^4;     //數(shù)碼管驅(qū)動數(shù)據(jù)
sbit SC=P2^5;     //數(shù)碼管驅(qū)動數(shù)據(jù)移動電平
sbit ST=P2^6;     //數(shù)碼管驅(qū)動鎖存輸出電平

//-----------按鍵值返回函數(shù)------------------------
unsigned int key_scan(void)
{
 unsigned int temp;
 bit find=0; 
 DAT=0xf0; 
    if((DAT&0xf0)!=0xf0)
{
     find=1;
 if(key4==0){temp=3;}
 else if(key5==0){temp=2;}
 else if(key6==0){temp=1;}
 else if(key7==0){temp=0;}  
 DAT=0x0f;
 
 if(key3==0){temp+=12;}
 else if(key2==0){temp+=8;}
 else if(key1==0){temp+=4;}
 else if(key0==0){temp+=0;}    
}
if(find==1){return temp; }
else return 16; 
}
//----------------數(shù)碼管驅(qū)動輸出數(shù)字函數(shù)--------------
void output(unsigned char cnt)
{
 unsigned char i;
 for(i=0;i<8;i++)
 {
  SC=0;
  DA=cnt&0x80;
  SC=1;
  cnt<<=1;
 }
}

//-----------主函數(shù)顯示按鍵值-------------
void main(void)
{
 unsigned int kk;
 while(1)
 {
   kk=key_scan();
   output(table[kk/10]);
   DATA_number=0x0f;   //關(guān)閉顯示,位切換準備
   ST=0;                         /鎖存準備 
   ST=1;                        //數(shù)據(jù)鎖存到輸出
   H1=0;                          //打開顯示位0 
   output(table[kk%10]);
   DATA_number=0x0f;
   ST=0;
   ST=1;
   H2=0;
 }
}

//---------------------數(shù)碼管驅(qū)動芯片采用---74HC595----



 

關(guān)閉窗口

相關(guān)文章