CubeMx配置
使能内部时钟
使能中断
Keil代码配置
开启时钟源和使能全局中断由CubeMx配置
TIM_HandleTypeDef htim2;
/* TIM2 init function */
void MX_TIM2_Init(void)
{
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 0;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 65535;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
}
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
{
if(tim_baseHandle->Instance==TIM2)
{
/* USER CODE BEGIN TIM2_MspInit 0 */
/* USER CODE END TIM2_MspInit 0 */
/* TIM2 clock enable */
__HAL_RCC_TIM2_CLK_ENABLE();
/* TIM2 interrupt Init */
HAL_NVIC_SetPriority(TIM2_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(TIM2_IRQn);
/* USER CODE BEGIN TIM2_MspInit 1 */
/* USER CODE END TIM2_MspInit 1 */
}
}
配置定时器的中断周期
以ns为单位配置 传进去的cfg为时间 如图所示 传入1000000个ns 即为 1ms
TimerConfig(ptimer, SET_PERIOD_VALUE, 1000000);
void TimerConfig(TIM_HandleTypeDef *ptimer,uint8_t cmd,uint32_t cfg){
uint32_t freq = 0;
TIM_HandleTypeDef *htim = NULL;
htim = ptimer;
if(htim){
if(htim->Instance == TIM2){
freq = HAL_RCC_GetPCLK1Freq() * 2;
}
}else{
return;
}
freq = freq/1000000;
switch(cmd){
case SET_PRESCALER_VALUE:
__HAL_TIM_SET_PRESCALER(htim, cfg);
break;
case SET_CLKDIV_VALUE:
if(cfg == 1)
__HAL_TIM_SET_CLOCKDIVISION(htim, TIM_CLOCKDIVISION_DIV1);
else if(cfg == 2)
__HAL_TIM_SET_CLOCKDIVISION(htim, TIM_CLOCKDIVISION_DIV2);
else if(cfg == 4)
__HAL_TIM_SET_CLOCKDIVISION(htim, TIM_CLOCKDIVISION_DIV4);
break;
case SET_PERIOD_VALUE:{
uint32_t maxint = (0xffffffff)/freq; //防止cfg*freq后溢出
uint32_t period = 1;
if(cfg < maxint){ //根据传进来的时间计算 定时器需要配置的周期值
period = freq * cfg / 1000;
}else{
period = cfg / 1000 * freq;
}
uint32_t prescaler = (period >> 16) + 1; //如果周期大于0xffff 则进行分频
period = period / prescaler;
__HAL_TIM_SET_PRESCALER(htim, prescaler - 1);
__HAL_TIM_SET_AUTORELOAD(htim, period - 1);
break;
}
default:break;
}
HAL_TIM_GenerateEvent(htim, TIM_EGR_UG);
}
开启定时器中断
void TimerStart(TIM_HandleTypeDef *ptimer){
TIM_HandleTypeDef *htim = NULL;
htim = ptimer;
if(htim){
HAL_StatusTypeDef status = HAL_TIM_Base_Start_IT(htim);
if(status != HAL_OK){
LogDebug("HAL_TIM_Base_Start_IT ERROR\r\n");
}
}
}