有源和无源这里的"源"不是指电源,而是指震荡源。也就是说,有源蜂鸣器内部带震荡源,所以只要一通电就会叫。而无源内部不带震荡源,所以如果用直流信号无法令其鸣叫。必须用2K~5K的方波去驱动它。有源蜂鸣器往往比无源的贵,就是因为里面多个震荡电路。这就是通过驱动原理来分别的方法。
buzzer.h
#ifndef __BUZZER_H__
#define __BUZZER_H__
#include "stm32l0xx_hal.h"
//有源蜂鸣器引脚
#define BUZZER_PORT GPIOA
#define BUZZER_PIN GPIO_PIN_12
typedef enum
{
BUZZER_OFF = 0, // 停止
BUZZER_ON, // 开始
}BUZZER_STATUE_E;
typedef struct{
BUZZER_STATUE_E Buzzer_SW; //蜂鸣器开关
uint8_t Buzzer_Times; //蜂鸣器响的次数
uint32_t Buzzer_DUR; //蜂鸣器响的时长
uint32_t Buzzer_OFF_DUR; //蜂鸣器不响的时长
uint32_t Buzzer_TEMP;
}Buzzer_time_T;
extern Buzzer_time_T Buzzer_time;
void buzzer_ring(Buzzer_time_T *Buzzer_time_para);
void set_buzzer(uint8_t sw,uint8_t times,uint32_t on_time,uint32_t off_time);
#endif
buzzer.c
#include "buzzer.h"
Buzzer_time_T Buzzer_time;
//开蜂鸣器
static void open_buzzer(void)
{
HAL_GPIO_WritePin(BUZZER_PORT, BUZZER_PIN, GPIO_PIN_SET);
}
//关蜂鸣器
static void close_buzzer(void)
{
HAL_GPIO_WritePin(BUZZER_PORT, BUZZER_PIN, GPIO_PIN_RESET);
}
/*********************************************************
根据结构体Buzzer_time的Buzzer_SW、Buzzer_DUR、Buzzer_Times
三个参数确定蜂鸣器开关、每次时长和次数
*********************************************************/
void buzzer_ring(Buzzer_time_T *Buzzer_time_para)
{
static uint8_t flag, times_flag;
if(Buzzer_time_para->Buzzer_SW)
{
if((Buzzer_time_para->Buzzer_Times) && (times_flag == 0))
{
if(!flag)
{
flag = 1;
open_buzzer();
Buzzer_time_para->Buzzer_TEMP = HAL_GetTick();
}
if(HAL_GetTick()-Buzzer_time_para->Buzzer_TEMP > Buzzer_time_para->Buzzer_DUR)
{
flag = 0;
Buzzer_time_para->Buzzer_Times--;
close_buzzer();
if(Buzzer_time_para->Buzzer_Times == 0)
{
Buzzer_time_para->Buzzer_SW = BUZZER_OFF;
Buzzer_time_para->Buzzer_DUR = 0;
times_flag = 0;
}
else
{
times_flag = 1;
}
}
}
else if((Buzzer_time_para->Buzzer_Times) && (times_flag == 1))
{
if(HAL_GetTick()-Buzzer_time_para->Buzzer_TEMP > (Buzzer_time_para->Buzzer_DUR + Buzzer_time_para->Buzzer_OFF_DUR))
{
times_flag = 0;
}
}
}
else
{
close_buzzer();
}
}
/*********************************************************
设置蜂鸣器响的次数及相应时长
*********************************************************/
void set_buzzer(BUZZER_STATUE_E sw,uint8_t times,uint32_t on_time,uint32_t off_time)
{
Buzzer_time.Buzzer_SW = sw;
Buzzer_time.Buzzer_Times = times;
Buzzer_time.Buzzer_DUR = on_time;
Buzzer_time.Buzzer_OFF_DUR = off_time;
}
//for simple test
void test_buzzer(void)
{
set_buzzer(BUZZER_ON,3,1000,1000);
while(1)
{
buzzer_ring(&Buzzer_time);
}
}