出现问题
- 问题代码:
void timer_PWM_init(TIM_TypeDef *TIMx, uint32_t tim_ch)
{
LL_TIM_InitTypeDef TIM_InitStruct = {0};
timer_clk_irq_config(TIMx, 0);
TIM_InitStruct.Prescaler = 71;
TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP;
TIM_InitStruct.Autoreload = 999;
TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
LL_TIM_Init(TIMx, &TIM_InitStruct);
LL_TIM_DisableARRPreload(TIMx);
LL_TIM_OC_EnablePreload(TIMx, tim_ch);
TIM_OC_InitStruct.OCMode = LL_TIM_OCMODE_PWM1;
TIM_OC_InitStruct.OCState = LL_TIM_OCSTATE_DISABLE;
TIM_OC_InitStruct.OCNState = LL_TIM_OCSTATE_DISABLE;
TIM_OC_InitStruct.CompareValue = 500;
TIM_OC_InitStruct.OCPolarity = LL_TIM_OCPOLARITY_HIGH;
LL_TIM_OC_Init(TIMx, tim_ch, &TIM_OC_InitStruct);
LL_TIM_OC_DisableFast(TIMx, tim_ch);
LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_RESET);
LL_TIM_DisableMasterSlaveMode(TIMx);
timer_io_init();
}
void timer_PWM_freq_set(TIM_TypeDef *TIMx, uint32_t tim_ch, uint16_t freq)
{
LL_TIM_DisableCounter(TIMx);
LL_TIM_SetPrescaler(TIMx, 7200-1); // 10KHz
LL_TIM_SetAutoReload(TIMx, (uint16_t)((10000/freq))-1);
}
- 问题现象:
调用:timer_PWM_freq_set(TIM3, LL_TIM_CHANNEL_CH4, 1000)
PWM没问题,1KHz,占空比50%
但是,调用:timer_PWM_freq_set(TIM3,LL_TIM_CHANNEL_CH4,100)
出问题了,PWM一直是高定平。
问题解决
- 问题分析:
因为初始化PWM的频率为1K,计数周期为500,占空比为50%
但是在后面修改频率后并未修改计数周期,也就是频率为100HZ,计数周期还是500,计数周期大于频率了,于是就出现一直高电平的现象。(个人分析的,不知正确与否,应该是这样的。。。。)
- 解决方法:
修改频率的同时也要修改计数周期,要保证计数周期小于频率,不然占空比比周期还长,自然就一直高定平或者低电平了
- 代码修改:
/**
* @brief 设置PWM输出频率
* @param fre取值范围(1-10000)Hz
* @retval 设置完成频率之后不启动定时器
*/
void timer_PWM_freq_set(TIM_TypeDef *TIMx, uint32_t tim_ch, uint16_t freq)
{
LL_TIM_DisableCounter(TIMx);
LL_TIM_SetPrescaler(TIMx, 7200-1); // 10KHz
LL_TIM_SetAutoReload(TIMx, (uint16_t)((10000/freq))-1);
LL_TIM_OC_SetCompareCH4(TIMx, (uint16_t)((10000/freq)/2))
}