频率2.097Mhz , TIM2定时1s触发一次中断
1.TIM2初始化
HAL_TIM_Base_Init>HAL_TIM_ConfigClockSource>HAL_TIMEx_MasterConfigSynchronization
/**
* @brief TIM2 Initialization Function
* @param None
* @retval None
*/
TIM_HandleTypeDef htim2;
void MX_TIM2_Init(uint16_t time)
{
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
htim2.Instance = TIM2;
htim2.Init.Prescaler = 2000;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = time - 1;
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();
}
}
复制代码
2.TIM2 中断处理函数
/**
* @brief This function handles TIM2 global interrupt.
*/
void TIM2_IRQHandler(void)
{
HAL_TIM_IRQHandler(&htim2);
}
复制代码
3.主函数main
int main(void)
{
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
LED_Init();//LED初始化
MX_TIM2_Init(1001); //1s一次
HAL_TIM_Base_Stop_IT(&htim2);
HAL_TIM_Base_Start_IT(&htim2);
while(1)
{}
}
复制代码
4.TIM中断回调处理函数
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if(htim == &htim2)
{
HAL_GPIO_TogglePin(GPIOB,GPIO_PIN8);
}
} |