继续利用STM32CUBE这个工具配置并生成工程:
1、找到TIMER2,这里使用的是基本功能,没涉及到比较捕获等功能,所以这里只选择了时钟:
	 
2、选择了时钟,那么看看给TIMER2提供的时钟频率是多少,由下图可知是32MHZ:
	 
3、目标是让定时器每一秒钟触发一次中断,然后向终端打印一句字符串。开始配置分频系数以及周期:
	 
因为要触发中断,所以必须使能中断:
	 
这样基本是就OK了,生成工程后打开。在程序中已经自动添加了TIMER2的初始化函数,这里还需要加一句,那就是启动定时器并且允许中断。
MX_USART2_UART_Init(); HAL_TIM_Base_Start_IT(&htim2);
现在面临的最后一个问题就是,中断服务函数在哪里...,看下图:
	 
在HAL_TIM_IRQHandler这个函数里有这么一段:
  /* TIM Update event */
  if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET)
  {
    if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_UPDATE) !=RESET)
    {
      __HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE);
      HAL_TIM_PeriodElapsedCallback(htim);
    }
  }
	STM32CUBE生成的代码框架已经定好了,在HAL_TIM_IRQHandler里有定时器涉及到的所有中断事件,每一个事件都对应一个回调函数,上面那段就是这次所用到的。继续在这个.c文件中找HAL_TIM_PeriodElapsedCallback();
	
 
		 
	/**
  * @brief  Period elapsed callback in non blocking mode 
  * @param  htim: pointer to a TIM_HandleTypeDef structure that contains
  *                the configuration information for TIM module.
  * @retval None
  */
__weak void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* NOTE : This function Should not be modified, when the callback is needed,
            the __HAL_TIM_PeriodElapsedCallback could be implemented in the user file
   */
  
}
	
	
 
		 由g_flag作为标志来判断是否可以打印字符串:
	 
 
			 
		uint8_t g_flag = 0;
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* NOTE : This function Should not be modified, when the callback is needed,
            the __HAL_TIM_PeriodElapsedCallback could be implemented in the user file
   */
	g_flag = 1;
  
}
	  while (1)
  {
		if(1 == g_flag)
		{
			user_opt++;
			printf("timer-->%d\n\r",user_opt);
			g_flag = 0;
		}
  }
		
	

 
					
				
 
			
			
			
						
			 
					
				 
					
				 
					
				 我要赚赏金
 我要赚赏金 STM32
STM32 MCU
MCU 通讯及无线技术
通讯及无线技术 物联网技术
物联网技术 电子DIY
电子DIY 板卡试用
板卡试用 基础知识
基础知识 软件与操作系统
软件与操作系统 我爱生活
我爱生活 小e食堂
小e食堂

