本文用TIM6创建1毫秒定时器为例子,讲解定时器的用法。
#define BTIM_INT TIM6
#define BTIM_INT_IRQn TIM6_IRQn
#define BTIM_INT_IRQHandler TIM6_IRQHandler
#define BTIM_INT_CLK_ENABLE() do{ RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_TIM6, ENABLE); }while(0) /* 时钟使能 */
/**
* @brief 基本定时器TIMX定时中断初始化函数
* @note
* 基本定时器的时钟来自APB1, 当PRES ≥ 2分频的时候
* 基本定时器的时钟为APB1时钟的2倍, 而APB1为36M, 所以定时器时钟 = 72Mhz
* 定时器溢出时间计算方法: Tout = ((u16Arr + 1) * (u16Psc + 1)) / Ft us.
* Freq = Ft / ((u16Arr+1) * (u16Psc + 1)) => 72000000 / (72 * 1000) = 1000Hz
* Ft=定时器工作频率,单位:Mhz
*
* @param u16Psc : 时钟预分频数
* @param u16Arr : 自动重装值
* @retval 无
*/
void BTIM_Init(U16 u16Psc, U16 u16Arr)
{
NVIC_InitType NVIC_InitStructure;
TIM_TimeBaseInitType TIM_TimeBaseStructure;
/* PCLK1 = HCLK/4 */
RCC_ConfigPclk1(RCC_HCLK_DIV4);
/* TIMx clock enable */
BTIM_INT_CLK_ENABLE();
/* Enable the TIMx global Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = BTIM_INT_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* Time base configuration */
TIM_InitTimBaseStruct(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.Period = u16Arr;
TIM_TimeBaseStructure.Prescaler = u16Psc;
TIM_TimeBaseStructure.ClkDiv = 0;
TIM_TimeBaseStructure.CntMode = TIM_CNT_MODE_UP;
TIM_InitTimeBase(BTIM_INT, &TIM_TimeBaseStructure);
/* Prescaler configuration */
TIM_ConfigPrescaler(BTIM_INT, u16Psc, TIM_PSC_RELOAD_MODE_IMMEDIATE);
/* TIMx enable update irq */
TIM_ConfigInt(BTIM_INT, TIM_INT_UPDATE, ENABLE);
/* TIMx enable counter */
TIM_Enable(BTIM_INT, ENABLE);
}
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/xbzjackey/article/details/142731566
|