一、什么是蜂鸣器?
蜂鸣器是一种将电信号转换为声音信号的器件,常用来产生设备的按键音、报警音等提示信号。
蜂鸣器按驱动方式可分为有源蜂鸣器 和无源蜂鸣器:
有源蜂鸣器:内部自带振荡源,将正负极接上直流电压即可持续发声,频率固定。
无源蜂鸣器:内部不带振荡源,需要控制器提供振荡脉冲才可发声,调整提供振荡脉冲的频率,可发出不同频率的声音。
二、51蜂鸣器原理:
同理,一种单片机一个样,本篇只讲51。
蜂鸣器原理图:很简单,BZ接通即响,BZ则接通到五线四相步进电机上。
五线四相步进电机:BZ由P1_5控制,给1则蜂鸣器响。
内部原理图:(扩展)
三、音高:控制频率:
方法:定时器中断:
cpp
sbit Buzzer = P1 ^ 5;//蜂鸣器
//低音L,中音M,高音H,后面为数组FreqTable的对应位置
#define P 0
#define L1 1 //低音1
#define L1_ 2 //1#,右边'_'标明#
#define L2 3
#define L2_ 4
#define L3 5
#define L4 6
#define L4_ 7
#define L5 8
#define L5_ 9
#define L6 10
#define L6_ 11
#define L7 12
#define M1 13 //中音1
#define M1_ 14 //1#
#define M2 15
#define M2_ 16
#define M3 17
#define M4 18
#define M4_ 19
#define M5 20
#define M5_ 21
#define M6 22
#define M6_ 23
#define M7 24
#define H1 25 //高音1
#define H1_ 26 //1#
#define H2 27
#define H2_ 28
#define H3 29
#define H4 30
#define H4_ 31
#define H5 32
#define H5_ 33
#define H6 34
#define H6_ 35
#define H7 36
//前面0的目的是休止,后面是,音高所对应的,定时器起始时长
unsigned int FreqTable[] = { 0,63628,63731,63835,63928,64021,64103,64185,64260,64331,64400
,64463,64528,64580,64633, 64684, 64732,64777, 64820, 64860, 64898, 64934,64968,65000,
65030,65058, 65085,65110, 65134, 65157, 65178, 65198, 65217,65235,65252,65268, 65283, };
void Timer0_Routine() interrupt 1
{
if (FreqTable[FreqSelect])
{
TH0 = FreqTable[FreqSelect] / 256;
TL0 = FreqTable[FreqSelect] % 256 + 1;
Buzzer = !Buzzer;
}
}
三、实战:蜂鸣器播放音乐:小星星
cpp
//低音L,中音M,高音H,后面为数组FreqTable的对应位置
#define P 0
#define L1 1 //低音1
#define L1_ 2 //1#,右边'_'标明#
#define L2 3
#define L2_ 4
#define L3 5
#define L4 6
#define L4_ 7
#define L5 8
#define L5_ 9
#define L6 10
#define L6_ 11
#define L7 12
#define M1 13 //中音1
#define M1_ 14 //1#
#define M2 15
#define M2_ 16
#define M3 17
#define M4 18
#define M4_ 19
#define M5 20
#define M5_ 21
#define M6 22
#define M6_ 23
#define M7 24
#define H1 25 //高音1
#define H1_ 26 //1#
#define H2 27
#define H2_ 28
#define H3 29
#define H4 30
#define H4_ 31
#define H5 32
#define H5_ 33
#define H6 34
#define H6_ 35
#define H7 36
//前面0的目的是休止,后面是,音高所对应的,定时器起始时长
unsigned int FreqTable[] = { 0,63628,63731,63835,63928,64021,64103,64185,64260,64331,64400
,64463,64528,64580,64633, 64684, 64732,64777, 64820, 64860, 64898, 64934,64968,65000,
65030,65058, 65085,65110, 65134, 65157, 65178, 65198, 65217,65235,65252,65268, 65283, };
unsigned char Music_LittleStar[] = { 13,1,13,1,20,1,20,1,22,1,22,1,20,2,18,1,18,1,17,1,17,1,15,1,15,1,13,2,0xFF };
unsigned char FreqSelect, MusicSelect;
void main()
{
Time0_Init();
while (1)
{
if (Music[MusicSelect] != 0xFF)
{
FreqSelect = Music[MusicSelect];
MusicSelect++;
Delay(500 * Music[++MusicSelect]);
//停顿,让同一音符分开
TR0 = 0;
Buzzer = 0;
Delay(50);
TR0 = 1;
}
else
{
//播放结束
TR0 = 0;
Buzzer = 0;
while (1);
}
}
}
void Timer0_Routine() interrupt 1
{
if (FreqTable[FreqSelect])
{
TH0 = FreqTable[FreqSelect] / 256;
TL0 = FreqTable[FreqSelect] % 256 + 1;
Buzzer = !Buzzer;
}
}