1. 程式人生 > >STM32CUBEMX TIMER 學習筆記

STM32CUBEMX TIMER 學習筆記

 Previous post has been devoted to GPIO configuration, we learned how to turn on/off LEDs with the help of STM32Cube. So, today we will also toggle the LED, but we’ll do it through interrupt handler. Let’s configure one of STM32 timers to generate an interrupt every 500 ms.


Primarily we should create a new project, choose the MCU which we would like to use and set up the project as usual. After that we can proceed to the timer configuration. I’ll use TIM3 unit:

To enable the timer clock we should select the clock source for it (for example, internal clock). Furthermore, I’ve activated PD12, because one of the LEDs on my development board is connected to this pin. So, I have to set its mode to “General output”.

We’ve already enabled the timer unit, but it also requires some extra configuration. In order to do this we should open Configuration tab and double-click on TIM3 

button:

TIM3 is connected to APB1 bus which default frequency is 16 MHz (in one of the future posts I’ll describe how to set different frequencies of all busses). Let’s set the prescaler value to 16000 (in counter settings we should enter (PSC – 1) value). Thus, to calculate timer frequency we should divide APB1 frequency by 16000 prescaler:

f_T = 16 MHz / 16000 = 1000 Hz

Furthermore, we should set the proper value of counter period. If we set it to 499 (as shown at the screenshot), we’ll get the following value of timer period:

T = \frac{1}{f_T} * (499 + 1) = 0.5 s

And the final step of TIM3 configuration is enabling its interrupt. This can be done at the “Nvic Settings” tab. Finally, let’s start code generation! As the result we get the new project with timer initialization function and interrupt handler (it is located in a file called stm32f4xx_it.c).

What should also be done is starting the timer counting (HAL_TIM_Base_Start_IT() function) and adding some extra code into the interrupt handler in order to change the output state of PD12 (LED toggling):

int main(void)
{
 
  /* USER CODE BEGIN 1 */
 
  /* USER CODE END 1 */
 
  /* MCU Configuration----------------------------------------------------------*/
 
  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();
 
  /* Configure the system clock */
  SystemClock_Config();
 
  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_TIM3_Init();
 
  /* USER CODE BEGIN 2 */
 
  HAL_TIM_Base_Start_IT(&htim3);
 
  /* USER CODE END 2 */
 
  /* USER CODE BEGIN 3 */
  /* Infinite loop */
  while (1)
  {
 
  }
  /* USER CODE END 3 */
 
}

void TIM3_IRQHandler(void)
{
  /* USER CODE BEGIN TIM3_IRQn 0 */
 
  /* USER CODE END TIM3_IRQn 0 */
  HAL_TIM_IRQHandler(&htim3);
  /* USER CODE BEGIN TIM3_IRQn 1 */
 
  HAL_GPIO_TogglePin(GPIOD, GPIO_PIN_12);
 
  /* USER CODE END TIM3_IRQn 1 */
}

Now we can program the MCU and see the green led toggling every 500 ms!