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
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
1.2. Timer configuration
Clock source selection internal clock
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
calculation formula is as follows,
where Tout is the calculated time, and Tclk is The clock frequency
is calculated according to the formula, and the timing is 500ms
to enable the timer interrupt
1.4, generate configuration
generate code
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 */