配置完成后在代码中完成定时器的中断回调函数,便可计算PWM的占空比、频率、周期。
/**
* [url=home.php?mod=space&uid=247401]@brief[/url] 定时器中断回调函数
* [url=home.php?mod=space&uid=536309]@NOTE[/url] htim 定时器句柄
*/
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
if(htim == &htim2)
{
if(htim2.Channel == HAL_TIM_ACTIVE_CHANNEL_1)
{
/* 记录TIM2_CCR1的值 */
PWM_RisingCount = HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_1);
if(PWM_RisingCount != 0 && PWM_FallingCount!= 0)
{
PWM_Duty = (float)(PWM_FallingCount / PWM_RisingCount);//占空比
PWM_Period = PWM_RisingCount*0.000001f; //周期
PWM_Frequency = 1/PWM_Period; //频率
}
}
else if(htim2.Channel == HAL_TIM_ACTIVE_CHANNEL_2)
{
/* 记录TIM2_CCR2的值 */
PWM_FallingCount = HAL_TIM_ReadCapturedValue(&htim2,TIM_CHANNEL_2);
}
}
}
|