1.进行恰当的TIM基本设置,设置自动重载寄存器值为最大值0xFFFF。
/* Time base configuration */
TIM_TimeBaseStructure.TIM_Period = 0xFFFF; //
设置自动重载寄存器值为最大值
TIM_TimeBaseStructure.TIM_Prescaler = UserdefinedPrescaler; //
自定义预分频
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
2.设置捕获/比较通道,工作在输出比较定时模式
/* Output Compare Timing Mode configuration: Channel1 */
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing; //
输出比较定时模式
TIM_OCInitStructure.TIM_Channel = TIM_Channel_1;
TIM_OCInitStructure.TIM_Pulse = Userdefined_Period; //
用户定义定时的周期
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInit(TIM4, &TIM_OCInitStructure);
3.通过设TIMx_CCMRx的OCxPE位为0关闭预载入寄存器,这样对TIMx_CCRx的修改会即时生效,打开相应通道的捕获/比较中断
TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Disable); //关闭预载入寄存器
TIM_ITConfig(TIM4, TIM_IT_CC1, ENABLE); // 打开捕获比较中断
4.根据需要设置定时器的捕获比较寄存器值(TIMx_CCRx),并在输出比较中断发生时,刷新该寄存器的值
5.在每次中断中, TIMx_CCRx += Userdefined_Period ,修改Userdefined_Period可即时修改定时的周期
void TIM4_IRQHandler(void)
{
u16 capture;
if (TIM_GetITStatus(TIM4, TIM_IT_CC1) != RESET)
{
TIM_ClearITPendingBit(TIM4, TIM_IT_CC1);
capture = TIM_GetCapture1(TIM4);
// 设置新的CCRx值
TIM_SetCompare1(TIM4, capture + Userdefined_Period);
User_Application(); // 用户程序
}
} |