按键发音/*名称:按键发音说明:按下不同的按键会是SOUNDER发出不同频率的声音。本例使用延时函数实现不同频率的声音输出,以后也可使用定时器*/#includereg51.h#defineucharunsignedchar#defineuintunsignedintsbitBEEP=P3^7;sbitK1=P1^4;sbitK2=P1^5;sbitK3=P1^6;sbitK4=P1^7;//延时voidDelayMS(uintx){uchart;while(x--)for(t=0;t120;t++);}//按周期t发音voidPlay(uchart){uchari;for(i=0;i100;i++){BEEP=~BEEP;DelayMS(t);}BEEP=0;}voidmain(){P1=0xff;BEEP=0;while(1){if(K1==0)Play(1);if(K2==0)Play(2);if(K3==0)Play(3);if(K4==0)Play(4);}}播放音乐/*名称:播放音乐说明:程序运行时播放生日快乐歌,未使用定时器中断,所有频率完全用延时实现*/#includereg51.h#defineucharunsignedchar#defineuintunsignedintsbitBEEP=P3^7;//生日快乐歌的音符频率表,不同频率由不同的延时来决定ucharcodeSONG_TONE[]={212,212,190,212,159,169,212,212,190,212,142,159,212,212,106,126,159,169,190,119,119,126,159,142,159,0};//生日快乐歌节拍表,节拍决定每个音符的演奏长短ucharcodeSONG_LONG[]={9,3,12,12,12,24,9,3,12,12,12,24,9,3,12,12,12,12,12,9,3,12,12,12,24,0};//延时voidDelayMS(uintx){uchart;while(x--)for(t=0;t120;t++);}//播放函数voidPlayMusic(){uinti=0,j,k;while(SONG_LONG[i]!=0||SONG_TONE[i]!=0){//播放各个音符,SONG_LONG为拍子长度for(j=0;jSONG_LONG[i]*20;j++){BEEP=~BEEP;//SONG_TONE延时表决定了每个音符的频率for(k=0;kSONG_TONE[i]/3;k++);}DelayMS(10);i++;}}voidmain(){BEEP=0;while(1){PlayMusic();//播放生日快乐DelayMS(500);//播放完后暂停一段时间}}