1#include "mspm0_pwm.hpp"
5static constexpr uint32_t MAX_TIMER_LOAD = 65535;
6static constexpr uint32_t MAX_PRESCALER = 256;
7static constexpr uint32_t MAX_DIVIDE_RATIO = 8;
10 : timer_(res.timer), channel_(res.channel), clock_freq_(res.clock_freq)
12 ASSERT(timer_ !=
nullptr);
13 ASSERT(clock_freq_ > 0);
27 uint32_t period = DL_Timer_getLoadValue(timer_);
28 uint32_t compare_value = 0;
29 DL_TIMER_COUNT_MODE count_mode = DL_Timer_getCounterMode(timer_);
33 case DL_TIMER_COUNT_MODE_DOWN:
34 compare_value =
static_cast<uint32_t
>(
static_cast<float>(period) * (1.0f - value));
37 case DL_TIMER_COUNT_MODE_UP:
38 case DL_TIMER_COUNT_MODE_UP_DOWN:
39 compare_value =
static_cast<uint32_t
>(
static_cast<float>(period) * value);
46 if (compare_value > period)
48 compare_value = period;
51 DL_Timer_setCaptureCompareValue(timer_, compare_value, channel_);
58 DL_Timer_ClockConfig config;
59 DL_Timer_getClockConfig(timer, &config);
60 return timer_clock_hz * (
static_cast<uint32_t
>(config.divideRatio) + 1U) *
61 (
static_cast<uint32_t
>(config.prescale) + 1U);
66 const uint32_t SOURCE_CLOCK = clock_freq_;
72 const uint32_t TOTAL_CYCLES_NEEDED = SOURCE_CLOCK / config.
frequency;
73 uint32_t min_total_prescale = (TOTAL_CYCLES_NEEDED + MAX_TIMER_LOAD) >> 16;
74 if (min_total_prescale == 0)
76 min_total_prescale = 1;
79 uint32_t best_div = (min_total_prescale + MAX_PRESCALER - 1) >> 8;
80 if (best_div > MAX_DIVIDE_RATIO)
89 uint32_t best_prescaler = (min_total_prescale + best_div - 1) / best_div;
90 if (best_prescaler == 0)
95 uint32_t best_load = (SOURCE_CLOCK / (best_div * best_prescaler * config.
frequency));
102 DL_Timer_ClockConfig clock_config;
103 DL_Timer_getClockConfig(timer_, &clock_config);
105 clock_config.divideRatio =
static_cast<DL_TIMER_CLOCK_DIVIDE
>(best_div - 1);
106 clock_config.prescale =
static_cast<uint8_t
>(best_prescaler - 1);
108 DL_Timer_setClockConfig(timer_, &clock_config);
109 DL_Timer_setLoadValue(timer_, best_load);
116 DL_Timer_startCounter(timer_);
122 DL_Timer_stopCounter(timer_);
ErrorCode Disable()
禁用 PWM 输出 / Disables the PWM output.
static uint32_t SourceClockFromSysCfg(GPTIMER_Regs *timer, uint32_t timer_clock_hz)
由 SysConfig 的定时器时钟反推源时钟 / Source clock from SysConfig's timer clock.
ErrorCode SetDutyCycle(float value)
设置 PWM 信号的占空比 / Sets the duty cycle of the PWM signal.
ErrorCode SetConfig(Configuration config)
配置 PWM 参数 / Configures the PWM settings.
ErrorCode Enable()
启用 PWM 输出 / Enables the PWM output.
LibXR 命名空间 / LibXR namespace.
ErrorCode
定义错误码枚举 / Defines an enumeration for error codes
@ NOT_SUPPORT
不支持 / Not supported
@ OK
操作成功 / Operation successful
@ ARG_ERR
参数错误 / Argument error
PWM 配置参数 / Configuration parameters for PWM.
uint32_t frequency
PWM 信号的频率(Hz) / PWM signal frequency in Hz.