一、训练任务
在CT107D单片机综合训练平台上,首先将J5处的跳帽接到1-2引脚, 使按键S4-S19按键组成4X4的矩阵键盘。在扫描按键的过程中,发现有按键触发信号后(不做去抖动),待按键松开后,在数码管的第一位显示相应的数字:从左至右,从上倒下,依次显示0~F.
二、原理图
从左端输入低电平为0时,即为扫描该行,如果按键按下,右端输出低电平为0,如果按键没按下,右端输出高电平为1。
对所有行进行输入,如1011,则是对第二行进行扫描,然后对列依次进行检测,检测到1,则是没有按下,检测到0则按键按下。
三、代码展示
#include <reg52.h> typedef unsigned int uint; typedef unsigned char uchar; sfr P4 = 0XC0; sbit R1 = P3^0; sbit R2 = P3^1; sbit R3 = P3^2; sbit R4 = P3^3; sbit C4 = P3^4; sbit C3 = P3^5; sbit C2 = P4^2; //P36 -> P42 sbit C1 = P4^4; //P37 -> P44 void DelayK(uint n) { while(n--); } uchar code SMG_duanma[18] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90, 0x88,0x80,0xc6,0xc0,0x86,0x8e, 0xbf,0x7f};//分别是0-9(对应下标),A-F,“-”,“.” //配置HC138 void SelectHC138(uchar channel) { switch(channel) { case 4: P2 = (P2 & 0X1F) | 0X80; break; case 5: P2 = (P2 & 0X1F) | 0Xa0; break; case 6: P2 = (P2 & 0X1F) | 0Xc0; break; case 7: P2 = (P2 & 0X1F) | 0Xe0; break; } } //初始化系统 void Initsys() { SelectHC138(5); P0 = 0X00;//关闭蜂鸣器和继电器 SelectHC138(4); P0 = 0XFF;//关闭LED } void DisplayKeyNum(uchar dat) { SelectHC138(6); P0 = 0X01; SelectHC138(7); P0 = SMG_duanma[dat]; } uchar key_num; void ScanKeyMulti() { R1 = 0; R2 = R3 = R4 = 1; C1 = C2 = C3 = C4 = 1; if(C1 == 0) { key_num = 0; DisplayKeyNum(key_num); while(C1 == 0); } else if(C2 == 0) { key_num = 1; DisplayKeyNum(key_num); while(C2 == 0); } else if(C3 == 0) { key_num = 2; DisplayKeyNum(key_num); while(C3 == 0); } else if(C4 == 0) { key_num = 3; DisplayKeyNum(key_num); while(C4 == 0); } R2 = 0; R1 = R3 = R4 = 1; C1 = C2 = C3 = C4 = 1; if(C1 == 0) { key_num = 4; DisplayKeyNum(key_num); while(C1 == 0); } else if(C2 == 0) { key_num = 5; DisplayKeyNum(key_num); while(C2 == 0); } else if(C3 == 0) { key_num = 6; DisplayKeyNum(key_num); while(C3 == 0); } else if(C4 == 0) { key_num = 7; DisplayKeyNum(key_num); while(C4 == 0); } R3 = 0; R2 = R1 = R4 = 1; C1 = C2 = C3 = C4 = 1; if(C1 == 0) { key_num = 8; DisplayKeyNum(key_num); while(C1 == 0); } else if(C2 == 0) { key_num = 9; DisplayKeyNum(key_num); while(C2 == 0); } else if(C3 == 0) { key_num = 10; DisplayKeyNum(key_num); while(C3 == 0); } else if(C4 == 0) { key_num = 11; DisplayKeyNum(key_num); while(C4 == 0); } R4 = 0; R2 = R3 = R1 = 1; C1 = C2 = C3 = C4 = 1; if(C1 == 0) { key_num = 12; DisplayKeyNum(key_num); while(C1 == 0); } else if(C2 == 0) { key_num = 13; DisplayKeyNum(key_num); while(C2 == 0); } else if(C3 == 0) { key_num = 14; DisplayKeyNum(key_num); while(C3 == 0); } else if(C4 == 0) { key_num = 15; DisplayKeyNum(key_num); while(C4 == 0); } } void main() { Initsys(); while(1) { ScanKeyMulti(); } }
注意事项
1.眺帽接到KBD,才是矩阵键盘
2.在头文件reg52.h中没有定义P4的地址,需要自己配置,为sfr P4 = 0XC0
3.看电路图是否引脚是否发生变