從零開始學(xué)單片機(八)蜂鳴器唱歌
單片機上的蜂鳴器結(jié)構(gòu)非常的簡單
只要給一個0,它就會“叫”。讓它唱歌的原理很簡單,聲音大小是固定的,讓它的頻率變化,就能讓它發(fā)出不同的音符。
代碼中在軟件循環(huán)延時過程中,依次給它一個固定頻率的方波,讓它唱起來。
//晶振11.0592
#include
sbit speaker=P2^3;
unsigned char byteTH0,byteT0L,duration;
// 小星星句子,三個一組,第一個表示音符,第二個表示音階,第三個表示延時長度(單位約等于0.1s)
code unsigned char music[]={
1,2,2, 1,2,2, 5,2,2, 5,2,2, 6,2,2, 6,2,2, 5,2,4,
4,2,2, 4,2,2, 3,2,2, 3,2,2, 2,2,2, 2,2,2, 1,2,4,
5,2,2, 5,2,2, 4,2,2, 4,2,2, 3,2,2, 3,2,2, 2,2,4,
5,2,2, 5,2,2, 4,2,2, 4,2,2, 3,2,2, 3,2,2, 2,2,4,
1,2,2, 1,2,2, 5,2,2, 5,2,2, 6,2,2, 6,2,2, 5,2,4,
4,2,2, 4,2,2, 3,2,2, 3,2,2, 2,2,2, 2,2,2, 1,2,4 };
//定時器計時初值,高八位,代表不同音符的頻率
code unsigned char FREQH[]={
0xF2,0xF3,0xF5,0xF5,0xF6,0xF7,0xF8,
0xF9,0xF9,0xFA,0xFA,0xFB,0xFB,0xFC,
0xFC,0xFC,0xFD,0xFD,0xFD,0xFD,0xFE,
0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFF,} ;
//定時器計時初值,低八位,代表不同音符的頻率
code unsigned char FREQL[]={
0x42,0xC1,0x17,0xB6,0xD0,0xD1,0xB6,
0x21,0xE1,0x8C,0xD8,0x68,0xE9,0x5B,
0x8F,0xEE,0x44, 0x6B,0xB4,0xF4,0x2D,
0x47,0x77,0xA2,0xB6,0xDA,0xFA,0x16,};
void song();
void delay(unsigned char t);
void main(void)
{
unsigned char index, step;
TMOD=1;
EA=1;
ET0=1;
while(1)
{
step=0;
while(step<126)
{
index = music[step] + 7 * music[step+1] - 1;
byteTH0 = FREQH[index];
byteT0L = FREQL[index];
duration = music[step+2];
step += 3;
song();
}
delay(10);
}
}
void timer0() interrupt 1
{
TR0=0;
speaker=!speaker;
TH0 = byteTH0;
TL0 = byteT0L;
TR0=1;
}
void delay(unsigned char t)
{
unsigned int i;
unsigned char j=80;
for(i=0; i
while(j--);
TR0=0;
}
void song()
{
TH0 = byteTH0;
TL0 = byteT0L;
TR0 = 1;
delay(duration);
}
編輯:admin 最后修改時間:2018-05-19