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

4*4鍵盤(pán)掃描代碼

作者:佚名   來(lái)源:本站原創(chuàng)   點(diǎn)擊數(shù):  更新時(shí)間:2013年10月21日   【字體:
#include<REG52.H>
//#include <intrins.H>
//#include "STC12C5A60AD.H"
//#include "STC12C5202AD.H"
#define uchar unsigned char //變量類(lèi)型標(biāo)識(shí)的宏定義
#define uint unsigned int
code uchar SEG7[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,
                   0x77,0x7c,0x39,0x5e,0x79,0x71};
#define OFF 1
#define ON 0
sbit P2_0=P2^0;  
sbit P1_0=P1^0;  
sbit P1_1=P1^1;  
sbit P1_2=P1^2;  
sbit P1_3=P1^3;  
sbit P1_4=P1^4;  
sbit P1_5=P1^5;  
sbit P1_6=P1^6;  
sbit P1_7=P1^7;
  
uchar key_scan(void);
//****************************************************   

 

 
void delay(uint k)
{
uint i,j;
for(i=0;i<k;i++)
 {
  for(j=0;j<120;j++);
 }  
}

 
void mcu_init(void)
{
 delay(1000);
}

 
/***********主函數(shù)*********/
void main(void)
{ uchar temp;
  mcu_init();
while(1)
{
temp=key_scan();
if(temp<16)    //如果有鍵按下
{P0=SEG7[temp];//顯示絲印符號(hào)
P2_0=ON;}
else P0=0x00;  //否則熄滅顯示
}
}
//********************************************
//鍵值設(shè)定
code uchar key_set[]=
{
1, 2, 3, 10,
4, 5, 6, 11,
7, 8, 9, 12,
15,0, 14,13
};
//********************************************
uchar key_scan(void)   
{uchar key;
 bit find=0;
 P1=0xf0; //輸入帶有上拉電阻。行輸入列輸出
  if((P1&0xf0)!=0xf0) //如果有鍵按下
   { find=1;              //發(fā)現(xiàn)標(biāo)志置1
     if(P1_4==0){key=0;}       //如果第1行有鍵按下
     else if(P1_5==0){key=4;}  //如果第2行有鍵按下
     else if(P1_6==0){key=8;}  //如果第3行有鍵按下
     else if(P1_7==0){key=12;} //如果第4行有鍵按下
     //翻轉(zhuǎn)端口方向,列輸入,行輸出
     P1=0x0f; //輸入帶有上拉電阻
     delay(10);
 
     if(P1_3==0)key+=0;      //如果第1列有鍵按下
     else if(P1_2==0)key+=1; //如果第2列有鍵按下
     else if(P1_1==0)key+=2; //如果第3列有鍵按下
     else if(P1_0==0)key+=3; //如果第4列有鍵按下
  }  
 if(find==1)return key_set[key];//有鍵按下,返回絲印符號(hào)值
 else return 16;                //無(wú)鍵按下,返回16
}

 
//  ---------------------------P13
//  |     ---------------------P12
//  |    |     ----------------P11
//  |    |    |     -----------P10
//  |1   |2   |3   |A
// -O----O----O----O-----------P14
//  |4   |5   |6   |B
// -O----O----O----O-----------P15
//  |7   |8   |9   |C
// -O----O----O----O-----------P16
//  |F   |0   |E   |D
// -O----O----O----O-----------P17
//  |    |    |    |
關(guān)閉窗口

相關(guān)文章