STM32Cube learning (2) - timer interrupt

0 Preface

MCU: STM32F407ZGT6;
emulator: ST Link V2;
development environment: STM32CubeIDE 1.10.1;
function description: use the timer interrupt method to realize the LED flashing according to the timer frequency.

Previous story summary:
STM32Cube learning (1) - lighting & configuration

Reference materials:
[STM32] HAL library STM32CubeMX tutorial six - timer interrupt
[STM32] HAL library - timer overflow interrupt

1. STM32CubeIDE configuration

Open CubeIDE, create a new project, and select the matching chip

1.1, configure the clock

insert image description here

In the clock configuration, configure as follows, enable HSE, PLLX72, external clock configuration is 8M, APB1 frequency divider is /2, and timer frequency is set to 72M
insert image description here

1.2. Timer configuration

Clock source selection internal clock
insert image description here

1.3. Parameter setting

PSC(Prescaler, prescaler) = 7199
Counter Mode (trigger mode) = up (count up)
Counter Period (arr, auto-reload value) = 4999
CKD (Internal Clock Division, clock frequency division factor) = disabled
auto-reload preload (auto-reload arr value) = enabled

TRGO: The trigger signal output of the timer outputs a signal when the timing time of the timer arrives
(for example: the timer update generates a TRGO signal to trigger the synchronous conversion of the ADC,) the
insert image description here
calculation formula is as follows,
where Tout is the calculated time, and Tclk is The clock frequency
insert image description here
is calculated according to the formula, and the timing is 500ms
insert image description here
to enable the timer interrupt
insert image description here

1.4, generate configuration

insert image description here
generate code
insert image description here

2. Code editing

Add the following code in main.c

Initialization interrupt in int main(void)

  /* USER CODE BEGIN 2 */
  //开启定时器中断
  HAL_TIM_Base_Start_IT(&htim2);
  /* USER CODE END 2 */

Callback function, the callback function will automatically reset the interrupt flag.

/* USER CODE BEGIN 4 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    
    
    static unsigned char ledState = 0;
    if (htim == (&htim2))
    {
    
    
        if (ledState == 0)
        	HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin,GPIO_PIN_RESET);
        else
        	HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin,GPIO_PIN_SET);
        ledState = !ledState;
    }
}
/* USER CODE END 4 */

Guess you like

Origin blog.csdn.net/u014798590/article/details/126644898
Recommended