有源的驱动可直接通过GPIO输出高低电平驱动:
#include "reg52.h"
#define uchar unsigned char
sbit beep = P2^0;
void Delay_10us(unsigned int t)
{
while(t--);
}
void main()
{
while(1)
{
beep = ~beep;
Delay_10us(50000);
}
}
无源需要进行占空比计算输出周期性电平来对无源蜂鸣器进行驱动 占空比计算时间:占空比=输出高电平的时间/周期 而占空比通常为小数,如0.21,但是程序中时常会用整数作为占空比参数 来计算输出高电平的时间,所以通常有输出高电平时间=占空比周期=占空比程序函数参数/100周期。 所以可以设计这样的函数:
void Pwm(unsigned char frequency, unsigned char duty)
{
unsigned char low = frequency * duty / 100;
unsigned char high = frequency - low;
beep = 0;
Delay_10us(low);
beep = 1;
Delay_10us(high);
}
由于蜂鸣器是低电平触发,所以电平对应的输出相反。
完整的程序为:
#include "reg52.h"
#define uchar unsigned char
sbit beep = P2^0;
void Delay_10us(unsigned int time)
{
while(time--);
}
void Pwm(unsigned char frequency, unsigned char duty)
{
unsigned char low = frequency * duty / 100;
unsigned char high = frequency - low;
beep = 0;
Delay_10us(low);
beep = 1;
Delay_10us(high);
}
void main()
{
while(1)
{
Pwm(2000, 10);
}
}
|