69 lines
2.1 KiB
C
69 lines
2.1 KiB
C
/* Includes ----------------------------------------------------------------- */
|
|
#include "bsp/led.h"
|
|
#include "bsp/bsp.h"
|
|
#include <tim.h>
|
|
|
|
/* Private define ----------------------------------------------------------- */
|
|
/* Private macro ------------------------------------------------------------ */
|
|
/* Private typedef ---------------------------------------------------------- */
|
|
/* Private variables -------------------------------------------------------- */
|
|
static uint32_t led_stats; // 使用位掩码记录每个通道的状态
|
|
|
|
/* Private function -------------------------------------------------------- */
|
|
/* Exported functions ------------------------------------------------------- */
|
|
|
|
int8_t BSP_LED_Set(BSP_LED_Channel_t ch, BSP_LED_Status_t s, float duty_cycle) {
|
|
if (duty_cycle > 1.0f) return BSP_ERR;
|
|
|
|
uint32_t tim_ch;
|
|
uint16_t pulse = (uint16_t)((1.0f - duty_cycle) * (float)UINT16_MAX); // 反转占空比
|
|
|
|
// 根据通道选择对应的定时器通道
|
|
switch (ch) {
|
|
case BSP_LED_RED:
|
|
tim_ch = TIM_CHANNEL_1;
|
|
break;
|
|
|
|
case BSP_LED_GREEN:
|
|
tim_ch = TIM_CHANNEL_2;
|
|
break;
|
|
|
|
case BSP_LED_BLUE:
|
|
tim_ch = TIM_CHANNEL_3;
|
|
break;
|
|
|
|
default:
|
|
return BSP_ERR; // 无效通道
|
|
}
|
|
|
|
// 设置 PWM 占空比
|
|
__HAL_TIM_SET_COMPARE(&htim3, tim_ch, pulse);
|
|
|
|
// 根据状态切换 LED
|
|
switch (s) {
|
|
case BSP_LED_ON:
|
|
HAL_TIM_PWM_Start(&htim3, tim_ch);
|
|
led_stats |= (1 << ch); // 设置对应通道的状态位
|
|
break;
|
|
|
|
case BSP_LED_OFF:
|
|
HAL_TIM_PWM_Stop(&htim3, tim_ch);
|
|
led_stats &= ~(1 << ch); // 清除对应通道的状态位
|
|
break;
|
|
|
|
case BSP_LED_TAGGLE:
|
|
if (led_stats & (1 << ch)) { // 如果当前通道已开启
|
|
HAL_TIM_PWM_Stop(&htim3, tim_ch);
|
|
led_stats &= ~(1 << ch); // 清除对应通道的状态位
|
|
} else { // 如果当前通道已关闭
|
|
HAL_TIM_PWM_Start(&htim3, tim_ch);
|
|
led_stats |= (1 << ch); // 设置对应通道的状态位
|
|
}
|
|
break;
|
|
|
|
default:
|
|
return BSP_ERR; // 无效状态
|
|
}
|
|
|
|
return BSP_OK;
|
|
} |