从零开始学单片机(八)蜂鸣器唱歌
单片机上的蜂鸣器结构非常的简单
只要给一个0,它就会“叫”。让它唱歌的原理很简单,声音大小是固定的,让它的频率变化,就能让它发出不同的音符。
代码中在软件循环延时过程中,依次给它一个固定频率的方波,让它唱起来。
//晶振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