要求:能够实现本单片机按下键盘,能够在数码管上显示键盘值。
连线:将片选CS0链接到KEY/LED CS。
1 #define LEDLen 6 2 3 xdata unsigned char OUTBIT _at_ 0x8002; // 位控制口 4 xdata unsigned char OUTSEG _at_ 0x8004; // 段控制口 5 xdata unsigned char IN _at_ 0x8001; // 键盘读入口 6 7 unsigned char LEDBuf[LEDLen]; // 显示缓冲 8 code unsigned char LEDMAP[] = { // 八段管显示码 9 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 10 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71 11 }; 12 13 void Delay(unsigned char CNT) 14 { 15 unsigned char i; 16 17 while (CNT-- !=0) 18 for (i=100; i !=0; i--); 19 } 20 21 void DisplayLED() 22 { 23 unsigned char i; 24 unsigned char Pos; 25 unsigned char LED; 26 27 Pos = 0x20; // 从左边开始显示 28 for (i = 0; i < LEDLen; i++) { 29 OUTBIT = 0; // 关所有八段管 30 LED = LEDBuf[i]; 31 OUTSEG = LED; 32 OUTBIT = Pos; // 显示一位八段管 33 Delay(1); 34 Pos >>= 1; // 显示下一位 35 } 36 } 37 38 code unsigned char KeyTable[] = { // 键码定义 39 0x16, 0x15, 0x14, 0xff, 40 0x13, 0x12, 0x11, 0x10, 41 0x0d, 0x0c, 0x0b, 0x0a, 42 0x0e, 0x03, 0x06, 0x09, 43 0x0f, 0x02, 0x05, 0x08, 44 0x00, 0x01, 0x04, 0x07 45 }; 46 47 unsigned char TestKey() 48 { 49 OUTBIT = 0; // 输出线置为0 50 return (~IN & 0x0f); // 读入键状态(高四位不用) 51 } 52 53 unsigned char GetKey() 54 { 55 unsigned char Pos; 56 unsigned char i; 57 unsigned char k; 58 59 i = 6; 60 Pos = 0x20; // 找出键所在列 61 do { 62 OUTBIT = ~ Pos; 63 Pos >>= 1; 64 k = ~IN & 0x0f; 65 } while ((--i != 0) && (k == 0)); 66 67 // 键值 = 列 x 4 + 行 68 if (k != 0) { 69 i *= 4; 70 if (k & 2) 71 i += 1; 72 else if (k & 4) 73 i += 2; 74 else if (k & 8) 75 i += 3; 76 77 OUTBIT = 0; 78 do Delay(10); while (TestKey()); // 等键释放 79 80 return(KeyTable[i]); // 取出键码 81 } else return(0xff); 82 } 83 84 void main() 85 { 86 LEDBuf[0] = 0xff; 87 LEDBuf[1] = 0xff; 88 LEDBuf[2] = 0xff; 89 LEDBuf[3] = 0xff; 90 LEDBuf[4] = 0x00; 91 LEDBuf[5] = 0x00; 92 93 while (1) { 94 DisplayLED(); 95 if (TestKey()) LEDBuf[5] = LEDMAP[GetKey() & 0x0f]; 96 } 97 }
实验结果:能够实现按下4*4矩阵键盘键码值在显示。