motor_cs103/User/system/bsp/pwms.h

120 lines
3.3 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @file pwms.h
* @brief Header file for PWMs module.
*
* This file contains the declarations and documentation for the PWMs module.
*
* @author xxx
* @date 2023-12-27 14:44:03
* @version 1.0
* @copyright Copyright (c) 2024 by xxx, All Rights Reserved.
*/
#ifndef __PWMS_H__
#define __PWMS_H__
#include "lib.h"
/**
* @brief Starts the PWM for a specific channel
* @param TIMx: TIM instance
* @param CHx: Channel to be started
* @retval None
*/
#define PWM_START(TIMx, CHx) \
do \
{ \
LL_TIM_EnableCounter(TIMx); \
LL_TIM_CC_EnableChannel(TIMx, CHx); \
} while (__LINE__ == -1)
/**
* @brief Stops the PWM for a specific channel
* @param TIMx: TIM instance
* @param CHx: Channel to be stopped
* @retval None
*/
#define PWM_STOP(TIMx, CHx) \
do \
{ \
LL_TIM_DisableCounter(TIMx); \
LL_TIM_CC_DisableChannel(TIMx, CHx); \
} while (__LINE__ == -1)
#define PWM_GET_ARR(TIMx) LL_TIM_GetAutoReload(TIMx)
#define PWM_GET_PSC(TIMx) LL_TIM_GetPrescaler(TIMx)
/**
* @brief Sets the PWM frequency
* @param TIMx: TIM instance
* @param CHx: Channel to be set
* @param COMPARE: Compare value
* @retval None
*/
static inline void PWM_SET_COMPARE(TIM_TypeDef *TIMx, uint32_t CHx, uint16_t COMPARE)
{
switch (CHx)
{
case LL_TIM_CHANNEL_CH1:
LL_TIM_OC_SetCompareCH1(TIMx, COMPARE);
break;
case LL_TIM_CHANNEL_CH2:
LL_TIM_OC_SetCompareCH2(TIMx, COMPARE);
break;
case LL_TIM_CHANNEL_CH3:
LL_TIM_OC_SetCompareCH3(TIMx, COMPARE);
break;
case LL_TIM_CHANNEL_CH4:
LL_TIM_OC_SetCompareCH4(TIMx, COMPARE);
break;
default:
break;
}
}
/**
* @brief 设置PWM占空比
*
* 设置指定定时器TIMx的指定通道CHx的PWM占空比。
*
* @param TIMx 定时器类型例如TIM1、TIM2等
* @param CHx 通道号例如TIM_CHANNEL_1、TIM_CHANNEL_2等
* @param DUTY 占空比范围在0到100之间
*/
static inline void PWM_SET_DUTY(TIM_TypeDef *TIMx, uint32_t CHx, uint16_t DUTY)
{
PWM_SET_COMPARE(TIMx, CHx, DUTY * LL_TIM_GetAutoReload(TIMx) / 100);
}
// 获取当前频率
static inline uint32_t PWM_GET_FREQ(TIM_TypeDef *TIMx)
{
return SystemCoreClock / (LL_TIM_GetPrescaler(TIMx) + 1) / (LL_TIM_GetAutoReload(TIMx) + 1);
}
/**
* @brief 获取指定通道的PWM比较值
*
* 根据给定的定时器指针和通道编号获取该通道的PWM比较值。
*
* @param TIMx 定时器指针指向一个TIM_TypeDef结构体
* @param CHx 通道编号取值范围为LL_TIM_CHANNEL_CH1到LL_TIM_CHANNEL_CH4
*
* @return 返回一个uint16_t类型的值表示指定通道的PWM比较值。如果通道编号无效则返回0。
*/
static inline uint16_t PWM_GET_COMPARE(TIM_TypeDef *TIMx, uint32_t CHx)
{
switch (CHx)
{
case LL_TIM_CHANNEL_CH1:
return LL_TIM_OC_GetCompareCH1(TIMx);
case LL_TIM_CHANNEL_CH2:
return LL_TIM_OC_GetCompareCH2(TIMx);
case LL_TIM_CHANNEL_CH3:
return LL_TIM_OC_GetCompareCH3(TIMx);
case LL_TIM_CHANNEL_CH4:
return LL_TIM_OC_GetCompareCH4(TIMx);
default:
return 0;
}
}
#endif ///< __PWMS_H__