要求:按下鍵盤,六個數位管流動顯示按下的值。
連線:将片選CS0接到key_LED_CS上
#include <reg52.h>
#define LEDLen 6
xdata unsigned char OUTBIT _at_ 0x8002; // 位控制口
xdata unsigned char OUTSEG _at_ 0x8004; // 段控制口
xdata unsigned char IN _at_ 0x8001; // 鍵盤讀入口
unsigned char LEDBuf[LEDLen]; // 顯示緩沖
code unsigned char LEDMAP[] = { // 八段管顯示碼 (點不顯示,0-F)
0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71
};
code unsigned char KeyTable[] = { // 鍵碼定義
0x16, 0x15, 0x14, 0xff,
0x13, 0x12, 0x11, 0x10,
0x0d, 0x0c, 0x0b, 0x0a,
0x0e, 0x03, 0x06, 0x09,
0x0f, 0x02, 0x05, 0x08,
0x00, 0x01, 0x04, 0x07
void Delay(unsigned char CNT)
{
unsigned char i;
while (CNT-- !=0)
for (i=100; i !=0; i--);
}
void DisplayLED()
unsigned char Pos;
unsigned char LED;
Pos = 0x20; // 從左邊開始顯示
for (i = 0; i < LEDLen; i++) {
OUTBIT = 0; // 關所有八段管
LED = LEDBuf[i];
OUTSEG = LED;
OUTBIT = Pos; // 顯示一位八段管
Delay(2);
Pos >>= 1; // 顯示下一位
}
unsigned char TestKey()
OUTBIT = 0; // 輸出線置為0
return (~IN & 0x0f); // 讀入鍵狀态(高四位不用)
unsigned char GetKey()
unsigned char k;
i = 6;
Pos = 0x20; // 找出鍵所在列
do {
OUTBIT = ~ Pos;
Pos >>= 1;
k = ~IN & 0x0f;
} while ((--i != 0) && (k == 0));
// 鍵值 = 列 x 4 + 行
if (k != 0)
{
i *= 4;
if (k & 2)
i += 1;
else if (k & 4)
i += 2;
else if (k & 8)
i += 3;
OUTBIT = 0;
do
Delay(10); while (TestKey()); // 等鍵釋放
return(KeyTable[i]); // 取出鍵碼
} else return(0xff);
void main()
{ unsigned int i=0;
LEDBuf[0] = 0x00; //如果設定為3F那麼最初第一個數位管顯示為0
LEDBuf[1] = 0x00;
LEDBuf[2] = 0x00;
LEDBuf[3] = 0x00;
LEDBuf[4] = 0x00;
LEDBuf[5] = 0x00;
while (1) {
DisplayLED();
if (TestKey())
{
LEDBuf[i++%6] = LEDMAP[GetKey() & 0x0f];
//LEDBuf[5]=LEDMP[GetKey()&0x0f];
}
}
本文轉自蓬萊仙羽51CTO部落格,原文連結:http://blog.51cto.com/dingxiaowei/1366582,如需轉載請自行聯系原作者