其中大量重复代码可优化。
如利用0x1f的与运算,达到仅处理P25\P26\P27口的效果后
再分case选择三个口
学习代码如下
#include "reg51.h"
sbit HC138_A = P2^5;
sbit HC138_B = P2^6;
sbit HC138_C = P2^7;
void initHC138(unsigned char n){
switch(n){
// case 4:
// HC138_A = 0;
// HC138_B = 0;
// HC138_C = 1; //Y4 = 1 可优化
// break;
//
// case 5:
// HC138_A = 1;
// HC138_B = 0;
// HC138_C = 1; //Y5 = 1 可优化
// break;
case 4:
P2 = (P2 & 0X1F) | 0X80; // 以下为优化后
break;
case 5:
P2 = (P2 & 0X1F) | 0XA0; //运算解释:用0x1f清空除了P2^5,P2^6,P2^7以外的P2口,
break; //然后方便对P2^5,P2^6,P2^7三个口一起进行取0或1的操作
}
}
void delay(unsigned int t){
while(t--);
while(t--);
}
void OUTPUTP0(unsigned char channel,unsigned char dat){ //dat是16进制
initHC138(channel);
P0 = dat;
}
void LEDRUNNING(){
unsigned char i;
for(i=0;i<3;i++){
OUTPUTP0(4,0x00);
delay(60000);
delay(60000);
OUTPUTP0(4,0xff);
delay(60000);
delay(60000);
}
for(i=1;i<=8;i++){
OUTPUTP0(4,(0xff << i));
delay(60000);
delay(60000);
}
OUTPUTP0(5,0x10); //继电器吸合
delay(60000);
delay(60000);
OUTPUTP0(5,0x00);
delay(60000);
delay(60000); //继电器断开
for(i=1;i<=8;i++){
OUTPUTP0(4,~(0xff << i));
delay(60000);
delay(60000);
}
OUTPUTP0(5,0X40); //蜂鸣器开
delay(60000);
delay(60000);
OUTPUTP0(5,0X00);
delay(60000);
delay(60000); //蜂鸣器关
}
void initsystem(){
OUTPUTP0(5,0X00);
}
void main(){
initsystem();
while(1){
LEDRUNNING();
}
}