功能说明:
1、可以实现设置蜂鸣器的音调
2、可以设置蜂鸣器连续鸣响次数
3、设置连续鸣响时间间隔
main.c
#include "mymain.h"
#include "dev_control.h"
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_TIM2_Init();
devInit();
devBuzzerSetNum(3); //设置鸣响次数3
devBuzzerSetLevel(unsigned char level); //设置音调等级
while (1)
{
devTask();
HAL_Delay(1);
}
}
buzzer.c
#include "dev_control.h"
#define DEV_TASK_PERIOD 1 //调用devTask的周期
devBuzzer_t devBuzzer = {0};
void devInit(void)
{
/*************************蜂鸣器************************/
devBuzzer.devBuzzerEnable = STATE_ENABLE;
devBuzzer.devBuzzerPeriod = 200; //周期200ms
devBuzzer.devBuzzerDuty = 100; //鸣响100ms
}
void devTask(void)
{
if(devBuzzer.devBuzzerEnable == STATE_ENABLE)
{
if(devBuzzer.devBuzzerNumber > 0)
{
devBuzzer.devBuzzerCount += DEV_TASK_PERIOD;
if(devBuzzer.devBuzzerCount <= devBuzzer.devBuzzerDuty)
{
HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_3);
}
else
{
HAL_TIM_PWM_Stop(&htim2,TIM_CHANNEL_3);
}
if(devBuzzer.devBuzzerCount == devBuzzer.devBuzzerPeriod)
{
devBuzzer.devBuzzerCount = 0;
devBuzzer.devBuzzerNumber--;
}
}
}
}
void devBuzzerSetLevel(unsigned char level)
{
switch(level)
{
case BUZZER_LEVEL_0:
devBuzzer.devBuzzerLevel = level;
__HAL_TIM_SET_PRESCALER(&htim2, 144-1);//设置时钟频率0.5Khz
break;
case BUZZER_LEVEL_1:
devBuzzer.devBuzzerLevel = level;
__HAL_TIM_SET_PRESCALER(&htim2, 72-1);//1Khz
break;
case BUZZER_LEVEL_2:
devBuzzer.devBuzzerLevel = level;
__HAL_TIM_SET_PRESCALER(&htim2, 36-1);//2Khz
break;
default:
break;
}
}
buzzer.h
#ifndef __DEV_CONTROL_H
#define __DEV_CONTROL_H
#include "main.h"
#include "gpio.h"
enum{
STATE_DISABLE,
STATE_ENABLE
};
enum{
BUZZER_LEVEL_0,
BUZZER_LEVEL_1,
BUZZER_LEVEL_2
};
//蜂鸣器控制结构体
typedef struct
{
unsigned char devBuzzerEnable; //使能
unsigned char devBuzzerLevel; //音调水平
unsigned char devBuzzerNumber; //连续鸣响次数
unsigned int devBuzzerDuty; //单次鸣响时长
unsigned int devBuzzerPeriod; //单次鸣响控制周期
unsigned int devBuzzerCount; //计数用于控制
} devBuzzer_t;
void devBuzzerSetNum(unsigned char num); //设置鸣响次数
void devBuzzerSetLevel(unsigned char level); //设置音调等级
#endif