Delay in HAL Library (HAL_Delay())

Reactionic picture Reactionic · Sep 5, 2017 · Viewed 40.9k times · Source

I'm trying to blink leds on my stm32f4 discovery. Somehow it stuck on delay function. I have changed SysTick interrupt priority to 0 and added IncTick(), GetTick() functions. What am I missing?

#include "stm32f4xx.h"                  // Device header
#include "stm32f4xx_hal.h"              // Keil::Device:STM32Cube HAL:Common


int main(){
    HAL_Init();

    __HAL_RCC_GPIOD_CLK_ENABLE();

    GPIO_InitTypeDef GPIO_InitStruct;

    GPIO_InitStruct.Pin = GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;

    HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);

    HAL_GPIO_WritePin(GPIOD, GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15, GPIO_PIN_SET);

    HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);   
    HAL_IncTick();
    HAL_GetTick();
    HAL_Delay(100);

    HAL_GPIO_WritePin(GPIOD, GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15, GPIO_PIN_RESET);
}

Answer

denis krasutski picture denis krasutski · Sep 6, 2017

Function HAL_IncTick() is called from SysTick_Handler() interrupt, which is usually implemented in stm32f4xx_it.c. You don't call this function from your code!

void SysTick_Handler(void)
{
    HAL_IncTick();
}

The function HAL_Init() initializes the SysTick timer to a 1ms interval and enables the associated interrupt. So, after calling HAL_Init() the function HAL_Delay() should be work properly.

NOTE: The STM32 HAL allows you to override (see keyword __weak) functions:

  • HAL_InitTick()
  • HAL_IncTick()
  • HAL_GetTick()
  • HAL_Delay()

So if you want to use the default delay mechanism you should not implement these functions in your code!