蜂鸣器分为有源蜂鸣器和无源蜂鸣器: 判断有源蜂鸣器和无源蜂鸣器可用万用表电阻档Rxl档测试:用黑表笔接蜂鸣器“+”引脚,红表笔在另一引脚上来回触碰,如果触发出咔咔声且电阻只有8Ω(或16Ω)的是无源蜂鸣器,如果能发出持续声音的,且电阻在几百Ω以上的,是有源蜂鸣器。
这里的源不是指电源,而是指震荡源。也就是说有源蜂鸣器内部带震荡源。所以只要一通电就会叫。而无源内部不带震荡源,所以如果用直流信号无法令其鸣叫,必须用2K~5K的方波去驱动。
原理图:
由于单片机的电流驱动不了蜂鸣器,因此需要增加一个三极管进行电流放大,原理图如下图所示:
代码:
//蜂鸣器
#include
#include"delay.h"
#define on 0 //宏定义,低电平0为开蜂鸣器
#define off 1
sbit speak=P2^3;
void main()
{
speak=on;
delay(500);
speak=off;
delay(500);
}
在流水灯亮的同时,蜂鸣器响,即两者同步,原理图如下图所示:
代码
//流水灯报警
#include
#include
#include"delay.h"
sbit speak=P2^3;
#define on 0
#define off 1
void main()
{
P1 = 0xfe; //1111 1110
while(1)
{
delay(500);
P1 = _crol_(P1,1); //将P1循环左移一位
speak=on;
delay(500);
speak=off;
}
}
#include
#include"delay.h"
#define uchar unsigned char
sbit speak =P2^3;
bit flag; //标志音乐输出脚电平的高低
uchar ptr=0x00;
uchar high;
uchar low;
uchar code music[]={
0xfc,0x44,0x7f, 0xfc,0x44,0x7f, 0xfc,0x44,0xff, 0xfa,0x68,0xff,
0xfd,0x23,0x7f, 0xfd,0x23,0x7f, 0xfd,0x23,0xff, 0xfc,0x44,0xff,
0xfc,0x44,0x7f, 0xfd,0x23,0x7f, 0xfd,0x82,0xff, 0xfd,0x82,0xff,
0xfd,0x23,0x7f, 0xfd,0x23,0x7f, 0xfc,0xac,0xff, 0xff,0xff,0xff,
0xfc,0xac,0x7f, 0xfd,0x23,0x7f, 0xfd,0x34,0xff, 0xfd,0x34,0xff,
0xfd,0x23,0x7f, 0xfc,0xac,0x7f, 0xfd,0x23,0xff, 0xfd,0x44,0xff,
0xfc,0x44,0x7f, 0xfd,0x23,0x7f, 0xfc,0xac,0xff, 0xfa,0x68,0xff,
0xfc,0x0c,0x7f, 0xfc,0xac,0x7f, 0xfc,0x44,0xff, 0xff,0xff,0xff,
0x00
}; //happy new year 歌曲
void Init(void); //函数声明
void main()
{
uchar time;
Init();
TH0=high;
TL0=low;
while(1)
{
if(music[ptr]!=0xff&&music[ptr]!=0x00)
{
TR0=0;
speak=1;
delay(10);
high=music[ptr];
low= music[ptr+1];
time=music[ptr+2];
delay(time);
ptr+=3;
}
else if(music[ptr]==0xff)
{
time=music[ptr+2];
delay(time);
ptr+=3;
}
else
{
TR0=0;
speak=1;
delay(2000);
ptr=0;
}
}
}
void Count1(void) interrupt 1
{
TH0=high;
TL0=low;
if(flag==0)
{
speak=0;
flag=1;
}
else
{
speak=1;
flag=0;
}
}
void Init()
{
TMOD=0x01;
EA=1;
ET0=1;
}