/* 標題:蜂鳴器的使用 電路:P1.0口接P11 */ #include "sys.h"//包含延時函數頭文件 #include <reg52.h> #include "beep1.h" sbit beez = P2^1;//位聲明,P2端口的第一位為蜂鳴器所用 void beep1() //非空函數+函數名 { while(1) //while死循環 { beez = 1; //賦高電平 delays(100); //調用延時函數 beez = 0; //賦低電平 delays(100); //同上 } } //---------------------------------------------- /* if not defined的簡寫為ifndef,c語言在對程序進行 編譯時,會先根據預處理命令進行“預處理”。C語言 編譯系統包括預處理,編譯和鏈接等部分。 */ #ifndef _BEEP1_H_ //先測試函數是否被宏定義過 #define _BEEP1_H_ void beep1(); //如果程序沒有被定義過,定義函數 //並編譯程序段beep1 #endif //終止if,條件指示符#endif的最主要目的是 //防止頭文件的重復包含和編譯。
/* 標題:蜂鳴器發出不同的音調 電路:p2.1口接P11 */ #include <reg52.h> #include "sys.h" #include "beep2.h" sbit beez = P2^1; void beep2(){ int i; while(1){ for(i = 0;i<1000;i++){ beez = 0; delays(100); beez = 1; delays(100); } for(i = 0;i<1000;i++){ beez = 0; delays(200); beez = 1; delays(200); } for(i = 0;i<1000;i++){ beez = 0; delays(50); beez = 1; delays(50); } for(i = 0;i<1000;i++){ beez = 0; delays(150); beez = 1; delays(150); } } } //---------------------------------------------- #ifndef _BEEP2_H_ #define _BEEP2_H_ void beep2(); #endif
/* 標題:蜂鳴器播放音樂 電路:p2.1口接P11 */ #include <reg52.h> #include "beep3.h" #include "sys.h" //八月桂花 unsigned char code music_code[] ={ 0x18, 0x30, 0x1C , 0x10, //格式為:頻率常數、節拍常數、頻率常數、節拍常數 0x20, 0x40, 0x1C , 0x10, 0x18, 0x10, 0x20 , 0x10, 0x1C, 0x10, 0x18 , 0x40, 0x1C, 0x20, 0x20 , 0x20, 0x1C, 0x20, 0x18 , 0x20, 0x20, 0x80, 0xFF , 0x20, 0x30, 0x1C, 0x10 , 0x18, 0x20, 0x15, 0x20 , 0x1C, 0x20, 0x20, 0x20 , 0x26, 0x40, 0x20, 0x20 , 0x2B, 0x20, 0x26, 0x20 , 0x20, 0x20, 0x30, 0x80 , 0xFF, 0x20, 0x20, 0x1C , 0x10, 0x18, 0x10, 0x20 , 0x20, 0x26, 0x20, 0x2B , 0x20, 0x30, 0x20, 0x2B , 0x40, 0x20, 0x20, 0x1C , 0x10, 0x18, 0x10, 0x20 , 0x20, 0x26, 0x20, 0x2B , 0x20, 0x30, 0x20, 0x2B , 0x40, 0x20, 0x30, 0x1C , 0x10, 0x18, 0x20, 0x15 , 0x20, 0x1C, 0x20, 0x20 , 0x20, 0x26, 0x40, 0x20 , 0x20, 0x2B, 0x20, 0x26 , 0x20, 0x20, 0x20, 0x30 , 0x80, 0x20, 0x30, 0x1C , 0x10, 0x20, 0x10, 0x1C , 0x10, 0x20, 0x20, 0x26 , 0x20, 0x2B, 0x20, 0x30 , 0x20, 0x2B, 0x40, 0x20 , 0x15, 0x1F, 0x05, 0x20 , 0x10, 0x1C, 0x10, 0x20 , 0x20, 0x26, 0x20, 0x2B , 0x20, 0x30, 0x20, 0x2B , 0x40, 0x20, 0x30, 0x1C , 0x10, 0x18, 0x20, 0x15 , 0x20, 0x1C, 0x20, 0x20 , 0x20, 0x26, 0x40, 0x20 , 0x20, 0x2B, 0x20, 0x26 , 0x20, 0x20, 0x20, 0x30 , 0x30, 0x20, 0x30, 0x1C , 0x10, 0x18, 0x40, 0x1C , 0x20, 0x20, 0x20, 0x26 , 0x40, 0x13, 0x60, 0x18 , 0x20, 0x15, 0x40, 0x13 , 0x40, 0x18, 0x80, 0x00 }; unsigned char* pin;//頻率 unsigned char* pai;//節拍 sbit beez = P2^1; void beep3() { int i,j; play://為goto所用,當程序執行到goto play時,重回此 pin = music_code; pai = pin+1; beez = 0; while(1) { if(pin == 0x00)//if條件函數 { //遇到結束符 goto play; } if(pai == 0xff) { //遇到休止符,等待一段時間 delays(200000); } for(i=0;i<(*pai)*10;i++)//for嵌套 { for(j=0;j<(*pin);j++) { beez = ~beez; } } pin += 2; pai += 2; } } //------------------------------------------------ #ifndef _BEEP3_H_ #define _BEEP3_H_ void beep3(); #endif