利用51微控制器,矩陣鍵盤按鍵顯示0--F在數碼管
程式碼如下:
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit we = P2^7;
sbit du = P2^6;
uchar code leddata[]={
0x3F, //"0"
0x06, //"1"
0x5B, //"2"
0x4F, //"3"
0x66, //"4"
0x6D, //"5"
0x7D, //"6"
0x07, //"7"
0x7F, //"8"
0x6F, //"9"
0x77, //"A"
0x7C, //"B"
0x39, //"C"
0x5E, //"D"
0x79, //"E"
0x71, //"F"
0x76, //"H"
0x38, //"L"
0x37, //"n"
0x3E, //"u"
0x73, //"P"
0x5C, //"o"
0x40, //"-"
0x00, //熄滅
0x00 //自定義
};
void delay(uint z)
{
uint x,y;
for(x = z; x > 0; x--)
for(y = 114; y > 0 ; y--);
}
uchar KeyScan() //帶返回值的子函式
{
uchar cord_l,cord_h;//宣告列線和行線的值的儲存變數
P3 = 0xf0;//1111 0000
if( (P3 & 0xf0) != 0xf0)//判斷是否有按鍵按下
{
delay(5);//軟體消抖
if( (P3 & 0xf0) != 0xf0)//判斷是否有按鍵按下
{
cord_l = P3 & 0xf0;// 儲存列線值
P3 = cord_l + 0x0f;
cord_h = P3 & 0x0f;// 儲存行線值
while( (P3 & 0x0f) != 0x0f );//鬆手檢測
return (cord_l + cord_h);//返回鍵值碼
}
}
}
void KeyPro()
{
switch( KeyScan() )
{
//第一行鍵值碼
case 0xee: P0 = leddata[0]; break;
case 0xde: P0 = leddata[1]; break;
case 0xbe: P0 = leddata[2]; break;
case 0x7e: P0 = leddata[3]; break;
//第二行鍵值碼
case 0xed: P0 = leddata[4]; break;
case 0xdd: P0 = leddata[5]; break;
case 0xbd: P0 = leddata[6]; break;
case 0x7d: P0 = leddata[7]; break;
//第三行鍵值碼
case 0xeb: P0 = leddata[8]; break;
case 0xdb: P0 = leddata[9]; break;
case 0xbb: P0 = leddata[10]; break;
case 0x7b: P0 = leddata[11]; break;
//第四行鍵值碼
case 0xe7: P0 = leddata[12]; break;
case 0xd7: P0 = leddata[13]; break;
case 0xb7: P0 = leddata[14]; break;
case 0x77: P0 = leddata[15]; break;
}
}
void main()
{
P0=0xff;
we = 1;//開啟位選
P0 = 0xfc;//顯示前兩位 11111100
we = 0;//鎖存位選
du = 1;//開啟段選端
while(1)
{
KeyPro();//提取鍵值碼並且送不同數值給數碼管顯示
}
}