02-蜂鸣器与继电器的基本控制
由原理图可知:
#include <REGX52.H>
void Delay(unsigned int t) {
while(t--);
while(t--);
}
// 74HC138
void _74HC138(unsigned char n) {
switch(n) { // 0001 1111
case 4: // LED使能
P2 = (P2 & 0x1f) | 0x80; // Y4 == 1000 0000
break;
case 5: // 蜂鸣器和继电器 // Y5 == 1010 0000
P2 = (P2 & 0x1f) | 0xa0;
break;
case 6: // 数码管位选 Y6 == 1100 0000
P2 = (P2 & 0x1f) | 0xc0;
break;
case 7: // 数码管段选
P2 = (P2 & 0x1f) | 0xe0; // Y7 == 1110 0000
break;
case 0:
P2 = (P2 & 0x1f) | 0x00;
break;
}
}
void SystemInit(void) {
// 关闭蜂鸣器和继电器
_74HC138(5);
P0 = 0x00;
// 保持LED为初始状态
_74HC138(4);
P0 = 0xff; // LED低电平点亮
_74HC138(0);
}
void check_Led(void) {
unsigned char i;
_74HC138(4);
for(i = 0; i < 8;i++) { // 1111 1111 << i 1111 1110
P0 = 0xff << i;
Delay(10000);
}
for(i = 0; i < 8;i++) { // ~(1111 1111) << i ===> 1111 1110
P0 = ~(0xff << i);
Delay(10000);
}
_74HC138(0);
}
void cleak_Display(void) {
unsigned char i;
_74HC138(7);
P0 = 0x00;
for(i =0;i<8;i++) {
_74HC138(6); // 1111 1110
P0 = ~(0xfe << i); // 0000 0001 0000 0011
Delay(60000);
}
for(i = 0; i<8;i++) {
_74HC138(6); //
P0 = 0xfe << i; // 1111 1110
Delay(60000);
}
_74HC138(0);
}
// channel 为74HC138 使能端 dat 为接收的数据
void OutputP0(unsigned char channel,unsigned char dat) {
_74HC138(channel);
P0 = dat;
}
void main() {
unsigned char i;
//SystemInit();
//check_Led();
//cleak_Display();
SystemInit();
// LED闪烁三遍熄灭
//_74HC138(4);
for(i=0;i<3;i++) {
OutputP0(4,0x00);
Delay(60000);
OutputP0(4,0xff);
Delay(60000);
}
//依次点亮LED
//_74HC138(4);
for(i = 0;i<8;i++) {
OutputP0(4,(0xfe<<i));
//P0 = 0Xfe << i; //
Delay(60000);
}
// 继电器吸合
OutputP0(5,0x10);
Delay(20000);
//P0 = 0x00;
//Delay(20000);
// 一次循环熄灭LED
//_74HC138(4);
for(i = 0;i<8;i++) {
OutputP0(4,~(0xfe<<i));
//P0 = ~(0Xfe << i);
Delay(60000);
}
// 蜂鸣器鸣叫
OutputP0(5,0x40);
Delay(20000);
//P0 = 0x00;
//Delay(20000);
//_74HC138(0);
}