- #include <reg52.h>
- #define uint unsigned int
- #define uchar unsigned char
- sbit BEEP=P2^3;//接喇叭或蜂鸣器的接口
- uint h,i;
- uint hz;
- uchar jiep;
- bit flag;
- uint code fre[]={ 64400,64524,64580,64684,64777,64820,64898,64968,65030,65058,65110,65157,65178,65217};
- uchar code song[]={6,9, 6,3, 7,12, 6,12, 9,12, 8,24, 6,9, 6,3, 7,12,
- 6,12, 10,12, 9,24, 6,9, 6,3, 13,12, 11,12, 8,12, 7,12,
- 12,9, 12,3, 11,12, 9,12, 10,12, 9,24}; //歌谱 2个一组(0,0)(音调,节拍)
- void init () //初始化
- {
- EA=1;
- TMOD=0x11;
- ET0=1;
- ET1=1;
- i=0;
- flag=1;
- }
- void sing()
- {
- if(flag==1)
- {
- h=song[i];
- jiep=song[i+1];
- i=i+2;
- if(i>46)
- i=0;
- hz=fre[h];
- TH0=(hz)/256;
- TL0=(hz)%256;
- flag=0;
- TR0=1;
- TR1=1;
- }
- }
- void main()
- {
- init();
- while(1)
- {
- sing();
- }
- }
- void time0() interrupt 1 //定时器0
- {
- TH0=(hz)/256;
- TL0=(hz)%256;
- if(!flag)
- BEEP=!BEEP;
- else
- TR0=0;
- }
- void time1() interrupt 3
- {
- TH1=(15536)/256;
- TL1=(15536)%256;
- --jiep;
- if(jiep==0)
- flag=1;
- }
复制代码 |