#include <REG52.H>
#include <INTRINS.H>
//頻率常數即音樂術語中的音調,而節拍常數即音樂術語中的多少拍;
//所以拿出譜子, 試探編吧!
sbit Beep = P1^5;
unsigned char n=0; //n為節拍常數變量
unsigned char code music_tab[] ={
0x1c, 0x30, 0x19, 0x30, 0x18, 0x40, 0x19, 0x30,
0x18, 0x30, 0x13, 0x30, 0x19, 0x18, 0x26, 0x30,
0x26, 0x30, 0x1c, 0x40, 0x20, 0x30, 0x1c, 0x30,
0x18, 0x30, 0x20, 0x60, 0x26, 0x30, 0x26, 0x30,
0x24, 0x40, 0x26, 0x30, 0x24, 0x30, 0x18, 0x40,
0x26, 0x60, 0x18, 0x20, 0x18, 0x20, 0x18, 0x20,
0x19, 0x40, 0x24, 0x30, 0x24, 0x30, 0x19, 0x30,
0x19, 0x60, 0x1c, 0x30, 0x19, 0x30, 0x18, 0x40,
0x19, 0x30, 0x18, 0x30, 0x13, 0x30, 0x19, 0x60,
0x26, 0x30, 0x26, 0x30, 0x1c, 0x40, 0x20, 0x30,
0x1c, 0x30, 0x18, 0x30, 0x20, 0x80, 0x26, 0x30,
0x24, 0x30, 0x24, 0x30, 0x18, 0x30, 0x19, 0x20,
0x19, 0x30, 0x18, 0x30, 0x15, 0x20, 0x15, 0x20,
0x13, 0x20, 0x18, 0x40, 0x18, 0x30, 0x19, 0x30,
0x1c, 0x20, 0x1c, 0x20, 0x19, 0x30, 0x20, 0x30,
0x1c, 0x60, 0x18, 0x30, 0x15, 0x30, 0x13, 0x40,
0x15, 0x30, 0x13, 0x30, 0x10, 0x30, 0x15, 0x60,
0x20, 0x30, 0x20, 0x30, 0x18, 0x30, 0x19, 0x30,
0x18, 0x30, 0x13, 0x30, 0x13, 0x60, 0x1c, 0x20,
0x19, 0x20, 0x18, 0x30, 0x19, 0x30, 0x15, 0x20,
0x15, 0x20, 0x18, 0x40, 0x20, 0x30, 0x20, 0x30,
0x12, 0x30, 0x13, 0x30, 0x15, 0x30, 0x18, 0x30,
0x13, 0xc0, 0x13, 0x80, 0x13, 0x30, 0x0e, 0x80,
0x10, 0x30, 0x10, 0x30, 0x13, 0x20, 0x15, 0x20,
0x18, 0x40, 0x18, 0x30, 0x15, 0x30, 0x18, 0x20,
0x15, 0x20, 0x15, 0x30, 0x10, 0x30, 0x13, 0x60,
0x13, 0x30, 0x0e, 0x60, 0x10, 0x60, 0x13, 0x20,
0x15, 0x20, 0x18, 0x40, 0x18, 0x30, 0x15, 0x30,
0x15, 0x20, 0x18, 0x20, 0x15, 0x30, 0x19, 0x30,
0x1c, 0x60, 0x1c, 0x30, 0x19, 0x30, 0x1c, 0xc0,
0x00,
};
void int0() interrupt 1 //采用中斷0 控制節拍
{ TH0=0xd8;
TL0=0xef;
n--;
}
void delay (unsigned char m) //控制頻率延時
{
unsigned i=3*m;
while(--i);
}
void delayms(unsigned char a) //豪秒延時子程序
{
while(--a); //采用while(--a) 不要采用while(a--); 各位可編譯一下看看匯編結果就知道了!
}
void main()
{ unsigned char p,m; //m為頻率常數變量
unsigned char i=0;
TMOD&=0x0f;
TMOD|=0x01;
TH0=0xd8;TL0=0xef;
IE=0x82;
play:
while(1)
{
a: p=music_tab[i];
if(p==0x00) { i=0, delayms(1000); goto play;} //如果碰到結束符,延時1秒,回到開始再來一遍
else if(p==0xff) { i=i+1;delayms(100),TR0=0; goto a;} //若碰到休止符,延時100ms,繼續取下一音符
else {m=music_tab[i++], n=music_tab[i++];} //取頻率常數 和 節拍常數
TR0=1; //開定時器1
while(n!=0) Beep=~Beep,delay(m); //等待節拍完成, 通過P1口輸出音頻(可多聲道哦!)
TR0=0; //關定時器1
}
}
|