频率
Fpwm = 100M / ((arr+1)*(psc+1))(单位:Hz)
- arr 是计数值
- psc 是预分频值
如:
3. 主频=100M
4. arr=100
5. psc=1000
100,000,000/100/1000=1000Hz
占空比
duty circle = TIM3->CCR1 / arr(单位:%)
TIM3->CCR1 是捕获比较寄存器值
从下面代码可以看出TIM3->CCR1 就是对应的sConfigOC.Pulse
arr对应htim5.Init.Period = 999;
psc对应htim5.Init.Prescaler = 99;
如果 arr=1000,TIM3->CCR1=500则pwm的占空比为50%,通过修改CCR1可以修改占空比,修改arr可以修改频率
/* TIM5 init function */
void MX_TIM5_Init(void)
{
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
htim5.Instance = TIM5;
htim5.Init.Prescaler = 99;
htim5.Init.CounterMode = TIM_COUNTERMODE_UP;
htim5.Init.Period = 999;
htim5.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
if (HAL_TIM_PWM_Init(&htim5) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim5, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 0;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
{
Error_Handler();
}
HAL_TIM_MspPostInit(&htim5);
}
static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config){
...
/* Set the Capture Compare Register value */
TIMx->CCR1 = OC_Config->Pulse;
}