從零開始學(xué)單片機(jī)(八)蜂鳴器唱歌
單片機(jī)上的蜂鳴器結(jié)構(gòu)非常的簡(jiǎn)單
只要給一個(gè)0,它就會(huì)“叫”。讓它唱歌的原理很簡(jiǎn)單,聲音大小是固定的,讓它的頻率變化,就能讓它發(fā)出不同的音符。
代碼中在軟件循環(huán)延時(shí)過程中,依次給它一個(gè)固定頻率的方波,讓它唱起來。
//晶振11.0592
#include
sbit speaker=P2^3;
unsigned char byteTH0,byteT0L,duration;
// 小星星句子,三個(gè)一組,第一個(gè)表示音符,第二個(gè)表示音階,第三個(gè)表示延時(shí)長(zhǎng)度(單位約等于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 };
//定時(shí)器計(jì)時(shí)初值,高八位,代表不同音符的頻率
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,} ;
//定時(shí)器計(jì)時(shí)初值,低八位,代表不同音符的頻率
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 最后修改時(shí)間:2018-05-19