1.你首先确认开发板上是无源蜂鸣器,否则响了也不是你想要的音乐声。
2.你的程序不能通过编译,蜂鸣器端口定义名称与程序中指令不符,delay延时程序漏写。修改后经仿真可以发出音乐声。
#include<reg52.h>
sbit BUZZ =P1^6;
unsigned int code NoteFrequ[]={523,587,659,698,784,880,988,1047,1175,1319,1397,1568,1760,1976};
unsigned int code NoteReload[]={
65536-(11059200/12)/(523*2),
65536-(11059200/12)/(587*2),
65536-(11059200/12)/(659*2),
65536-(11059200/12)/(698*2),
65536-(11059200/12)/(784*2),
65536-(11059200/12)/(880*2),
65536-(11059200/12)/(988*2),
65536-(11059200/12)/(1047*2),
65536-(11059200/12)/(1175*2),
65536-(11059200/12)/(1319*2),
65536-(11059200/12)/(1397*2),
65536-(11059200/12)/(1568*2),
65536-(11059200/12)/(1760*2),
65536-(11059200/12)/(1976*2),
};
bit enable =1;
bit tmrflag=0;
unsigned char T0RH=0xFF;
unsigned char T0RL=0x00;
void PlayTwoTiger();
void delay(unsigned int k)
{
unsigned int i,j;
for(i=k;i>0;i--)
for(j=110;j>0;j--);
}
void main()
{
unsigned int i;
EA=1;
TMOD=0x01;
TH0=T0RH;
TL0=T0RL;
ET0=1;
TR0=1;
while(1)
{
PlayTwoTiger();
for(i=0;i<40000;i++);
}
}
void PlayTwoTiger()
{
unsigned char beat;
unsigned char note;
unsigned int time=0;
unsigned int beatTime=0;
unsigned int soundTime=0;
unsigned char code TwoTigerNote[]={
1, 2, 3, 1, 1, 2, 3, 1, 3,4,5, 3,4,5,
5,6,5,4,3,1, 5,6,5,4,3,1, 1,5,1, 1,5,1,};
unsigned char code TwoTigerBeat[]={4, 4 , 4 ,4, 4 , 4 , 4 , 4, 4,4,8, 4,4,8,
3,1,3,1 ,4, 4, 3,1,3,1,4,4, 4,4,8, 4,4,8,};
for(beat=0;beat<sizeof(TwoTigerNote); )
{
while(!tmrflag);
{
BUZZ=0;
delay(1);
BUZZ=1;
delay(1);
}
tmrflag=0;
if(time==0)
{
note = TwoTigerNote[beat] - 1;
T0RH = NoteReload[note]>> 8;
T0RL = NoteReload[note];
beatTime = (TwoTigerBeat[beat] * NoteFrequ[note])>>2;
soundTime = beatTime - (beatTime>>2);
enable = 1;
time++;
}
else
{
if(time >=beatTime)
{
time =0;
beat++;
}
else
{
time++;
if(time==soundTime)
{
enable=0;
}
}
}
}
}
void InterruptTimer0() interrupt 1
{
TH0=T0RH;
TL0=T0RL;
tmrflag=1;
if(enable)
BUZZ=~BUZZ;
else
BUZZ=1;
}
|