CM_DOG/User/bsp/buzzer.c
2025-06-24 10:28:20 +08:00

37 lines
1.4 KiB
C

/* Includes ----------------------------------------------------------------- */
#include "bsp/buzzer.h"
#include <main.h>
#include <tim.h>
/* Private define ----------------------------------------------------------- */
/* Private macro ------------------------------------------------------------ */
/* Private typedef ---------------------------------------------------------- */
/* Private variables -------------------------------------------------------- */
/* Private function -------------------------------------------------------- */
/* Exported functions ------------------------------------------------------- */
int8_t BSP_Buzzer_Start(void) {
if (HAL_TIM_PWM_Start(&htim12, TIM_CHANNEL_2) == HAL_OK) return BSP_OK;
return BSP_ERR;
}
int8_t BSP_Buzzer_Set(float freq, float duty_cycle) {
if (freq <= 0.0f || duty_cycle < 0.0f || duty_cycle > 1.0f) return BSP_ERR;
uint32_t timer_clk = HAL_RCC_GetPCLK1Freq(); // 具体时钟频率请根据你的芯片和配置调整
uint32_t prescaler = htim12.Init.Prescaler + 1;
uint32_t period = (uint32_t)((float)timer_clk / (prescaler * freq)) - 1;
__HAL_TIM_SET_AUTORELOAD(&htim12, period);
uint32_t pulse = (uint32_t)(duty_cycle * (float)(period + 1));
__HAL_TIM_SET_COMPARE(&htim12, TIM_CHANNEL_2, pulse);
return BSP_OK;
}
int8_t BSP_Buzzer_Stop(void) {
if (HAL_TIM_PWM_Stop(&htim12, TIM_CHANNEL_2) == HAL_OK) return BSP_OK;
return BSP_ERR;
}