|
#include <reg52.h>
sbit BUZZ = P1^6; //蜂鳴器控制引腳
unsigned int code NoteFrequ[] = { //中音1-7和高音1-7對(duì)應(yīng)頻率列表
523, 587, 659, 698, 784, 880, 988, //中音1-7
1047, 1175, 1319, 1397, 1568, 1760, 1976 //高音1-7
};
unsigned int code NoteReload[] = { //中音1-7和高音1-7對(duì)應(yīng)的定時(shí)器重載值
65536 - (11059200/12) / (523*2), //中音1
65536 - (11059200/12) / (587*2), //2
65536 - (11059200/12) / (659*2), //3
65536 - (11059200/12) / (698*2), //4
65536 - (11059200/12) / (784*2), //5
65536 - (11059200/12) / (880*2), //6
65536 - (11059200/12) / (988*2), //7
65536 - (11059200/12) / (1047*2), //高音1
65536 - (11059200/12) / (1175*2), //2
65536 - (11059200/12) / (1319*2), //3
65536 - (11059200/12) / (1397*2), //4
65536 - (11059200/12) / (1568*2), //5
65536 - (11059200/12) / (1760*2), //6
65536 - (11059200/12) / (1976*2), //7
};
bit enable = 1; //蜂鳴器發(fā)聲使能標(biāo)志
bit tmrflag = 0; //定時(shí)器中斷完成標(biāo)志
unsigned char T0RH = 0xFF; //T0重載值的高字節(jié)
unsigned char T0RL = 0x00; //T0重載值的低字節(jié)
void PlayTwoTiger();
void main()
{
unsigned int i;
EA = 1; //使能全局中斷
TMOD = 0x01; //配置T0工作在模式1
TH0 = T0RH;
TL0 = T0RL;
ET0 = 1; //使能T0中斷
TR0 = 1; //啟動(dòng)T0
while (1)
{
PlayTwoTiger(); //播放樂(lè)曲--兩支老虎
for (i=0; i<40000; i++); //停止一段時(shí)間
}
}
/* 兩只老虎樂(lè)曲播放函數(shù) */
void PlayTwoTiger()
{
unsigned char beat; //當(dāng)前節(jié)拍索引
unsigned char note; //當(dāng)前節(jié)拍對(duì)應(yīng)的音符
unsigned int time = 0; //當(dāng)前節(jié)拍計(jì)時(shí)
unsigned int beatTime = 0; //當(dāng)前節(jié)拍總時(shí)間
unsigned int soundTime = 0; //當(dāng)前節(jié)拍需發(fā)聲時(shí)間
//兩只老虎音符表
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,
};
//兩只老虎節(jié)拍表,4表示一拍,1就是1/4拍,8就是2拍
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); ) //用節(jié)拍索引作為循環(huán)變量
{
while (!tmrflag); //每次定時(shí)器中斷完成后,檢測(cè)并處理節(jié)拍
tmrflag = 0;
if (time == 0) //當(dāng)前節(jié)拍播完則啟動(dòng)一個(gè)新節(jié)拍
{
note = TwoTigerNote[beat] - 1;
T0RH = NoteReload[note] >> 8;
T0RL = NoteReload[note];
//計(jì)算節(jié)拍總時(shí)間,右移2位相當(dāng)于除4,移位代替除法可以加快執(zhí)行速度
beatTime = (TwoTigerBeat[beat] * NoteFrequ[note]) >> 2;
//計(jì)算發(fā)聲時(shí)間,為總時(shí)間的0.75,移位原理同上
soundTime = beatTime - (beatTime >> 2);
enable = 1; //指示蜂鳴器開(kāi)始發(fā)聲
time++;
}
else //當(dāng)前節(jié)拍未播完則處理當(dāng)前節(jié)拍
{
if (time >= beatTime) //當(dāng)前持續(xù)時(shí)間到達(dá)節(jié)拍總時(shí)間時(shí)歸零,
{ //并遞增節(jié)拍索引,以準(zhǔn)備啟動(dòng)新節(jié)拍
time = 0;
beat++;
}
else //當(dāng)前持續(xù)時(shí)間未達(dá)到總時(shí)間時(shí),
{
time++; //累加時(shí)間計(jì)數(shù)
if (time == soundTime) //到達(dá)發(fā)聲時(shí)間后,指示關(guān)閉蜂鳴器,
{ //插入0.25*總時(shí)間的靜音間隔,
enable = 0; //用以區(qū)分連續(xù)的兩個(gè)節(jié)拍
}
}
}
}
}
/* T0中斷服務(wù)函數(shù),用于控制蜂鳴器發(fā)聲 */
void InterruptTimer0() interrupt 1
{
TH0 = T0RH; //重新加載重載值
TL0 = T0RL;
tmrflag = 1;
if (enable) //使能時(shí)反轉(zhuǎn)蜂鳴器控制電平
BUZZ = ~BUZZ;
else //未使能時(shí)關(guān)閉蜂鳴器
BUZZ = 1;
}
|
|