用51单片机演奏民歌茉莉花
源代码
#include
sbit Buzz = P3^1;
unsigned int code NoteFrequ[]={
523,587,659,698,784,880,988,
1047,1175,1319,1397,1568,1760,1976,
262,294,330,349,392,440,494};
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),
65536 - (11059200/12) /(262*2),
65536 - (11059200/12) /(294*2),
65536 - (11059200/12) /(330*2),
65536 - (11059200/12) /(349*2),
65536 - (11059200/12) /(392*2),
65536 - (11059200/12) /(440*2),
65536 - (11059200/12) /(494*2)};
bit enable = 1;
bit tmrflay = 0;
unsigned char T0RH = 0xff;
unsigned char T0RL = 0x00;
void PlayTwoTiger(); 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 PlayTwoTigerNote[]={
3,3,5,6,8,8,6,5,5,6,5,
3,3,5,6,8,8,6,5,5,6,5,
5,5,5,3,5,6,6,5,
3,2,3,5,3,2,1,1,2,1,
3,2,1,3,2,3,5,6,8,5,
2,3,5,2,3,1,20,19,
20,1,2,3,
1,2,1,20,19
};
unsigned char code PlayTwoBeat[]={
4,2,2,2,2,2,2,4,2,2,8,
4,2,2,2,2,2,2,4,2,2,8,
4,4,4,2,2,4,4,8,
4,2,2,4,2,2,4,2,2,8,
2,2,2,2,6,2,4,2,2,8,
4,2,2,2,2,2,2,8,
4,4,6,2,
2,2,2,2,16
};
for(beat=0; beat<sizeof(PlayTwoTigerNote);)
{
while(!tmrflay);
tmrflay = 0;
if(time == 0)
{
note = PlayTwoTigerNote[beat]-1;
T0RH = NoteReload[note]>>8;
T0RL = NoteReload[note];
beattime = (PlayTwoBeat[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 InterRupt() interrupt 1
{
TH0 =T0RH;
TL0 =T0RL;
tmrflay = 1;
if(enable)
{
Buzz=~Buzz;
}
else
{
Buzz=1;
}
}