以下内容位转载: 谢谢原作者的分享。
74HC165是一款并入串出的芯片,下图通过74HC165 读入8个按键状态,并用7个LED灯L1~L8分别对应S1~S8,来显示按键状态.
硬件连接图如下:
程序代码如下:
1//--------------------------------------------------------------------------2 //来源: http://hi.baidu.com/mculove/home3 //程序名称: 用74HC165读8个按键状态4 //晶振: 11.0592MHz;5 //MCU型号: STC89C52RC;6 //电路板型号: EBV-MV(51实验板);7 //--------------------------------------------------------------------------8 9 10 11 12 //--------------------------------------------------------------------------13 //硬件连接:14 //EBVn-[VCC] -> MVn-[--VCC--]15 //EBVn-[GND] -> MVn-[//GND//]16 //MVn-{EX3}-[Y0] -> MVn-{EX2}-[L1]17 //MVn-{EX3}-[Y1] -> MVn-{EX2}-[L2]18 //MVn-{EX3}-[Y2] -> MVn-{EX2}-[L3]19 //MVn-{EX3}-[Y3] -> MVn-{EX2}-[L4]20 //MVn-{EX3}-[Y4] -> MVn-{EX2}-[L5]21 //MVn-{EX3}-[Y5] -> MVn-{EX2}-[L6]22 //MVn-{EX3}-[Y6] -> MVn-{EX2}-[L7]23 //MVn-{EX3}-[Y7] -> MVn-{EX2}-[L8]24 // -> MVn-{EX2}-(VCC)25 // -> MVn-{EX3}-(VCC)26 27 //EBVn-[P10] -> MVn-{EX3}-[A]28 //EBVn-[P11] -> MVn-{EX3}-[B]29 //EBVn-[P12] -> MVn-{EX3}-[C]30 //EBVn-[P13] -> MVn-{EX3}-[G1]31 //--------------------------------------------------------------------------32 33 34 35 36 //--------------------------------------------------------------------------37 //实验结果:38 //当按下一个按键时候,对应的LED灯被点亮。如按下S1,则L1灯亮,按下S2,则L2灯亮......39 //--------------------------------------------------------------------------40 41 42 43 //------------------------------------------------------44 //头文件;45 #include46 47 #define HC165_nPL P3_5 //移位或载入选择信号48 #define HC165_CK P3_6 //时钟信号49 #define HC165_OUT P3_7 //数据输出50 51 //------------------------------------------------------52 void delay(void)53 {54 unsigned char i,j;55 for(i = 250;i > 0;i--)56 for(j = 200;j > 0;j--);57 }58 59 unsigned char HC165(void) //返回值为char型,8位60 {61 unsigned char i;62 unsigned char Temp;63 HC165_CK = 1; 64 HC165_nPL = 0; //HC165读按键65 HC165_nPL = 1; //暂停HC165读按键66 Temp = 0;67 if(HC165_OUT == 1) Temp |= 0x01; //此时HC165_OUT为Temp的最高位。68 for(i = 0;i < 7;i++) //需要移位7次,才能读完69 { 70 HC165_CK = 0; 71 HC165_CK = 1; //时钟上升沿,HC165移位 72 Temp <<= 1; //Temp左移一位,为新来的数据空出最后一位73 if(HC165_OUT == 1) //读入新来的数据到最后一位74 {75 Temp |= 0x01; 76 }77 }78 HC165_CK = 0; 79 return(Temp); //经过7次循环后,D6,D5,D4,D3,D2,D1,D0被依次读入Temp的7个位中80 }81 82 83 84 //------------------------------------------------------85 //程序入口;86 void main(void)87 {88 while(1)89 {90 P1 = HC165();91 delay();92 }93 }