Skip to main content
Graduate II
September 12, 2025
Question

Various uses of Delay in STM32

  • September 12, 2025
  • 2 replies
  • 351 views

This is to document various uses of delays like HAL_Delay() in STM32 code.

I have found 2 decent uses 

1. Put at the start of  /* USER CODE BEGIN 2 */ to stop the code from executing when we are reprogramming the board.

2. Put at the start of  /* USER CODE BEGIN 2 */ to give time to properly initialize DMA related functionality.

/* USER CODE BEGIN 2 */

HAL_Delay(2000);

HAL_UARTEx_ReceiveToIdle_DMA( &huart7,

gsm_response_buffer,

GSM_RESPONSE_BUFFER_SIZE);

__HAL_DMA_DISABLE_IT(&hdma_uart7_rx, DMA_IT_HT);

/* USER CODE END 2 */

without the delay the DMA reception was not working.

 

Please put any other / any modification anyone find / know here to make it as a central repository.

Edited by ST moderator to be inline with the community rules especially with the code sharing. In next time please use </> button to paste your code. Please read this post: How to insert source code

    This topic has been closed for replies.

    2 replies

    Super User
    September 12, 2025

    Right,

    but no need to wait so long time;

    i have/need it, because attached LCD/TFT etc. needs some time to be ready to work , so:

     ....
     MX_I2C1_Init();
     MX_ADC1_Init();
    
     /* USER CODE BEGIN 2 */
    
    // live variables decaration maybe - must - be here !!!!
    // initialise_monitor_handles();
    
    
     HAL_Delay(50);	// wait for LCD etc. power up ********************************
    ....

     

    50...100 ms usually good value here.

     

     

    Super User
    September 12, 2025

    @vishnu_illikkal wrote:

    1. Put at the start of  /* USER CODE BEGIN 2 */ to stop the code from executing when we are reprogramming the board


    That's only necessary if your code does stuff like putting the CPU to sleep, and/or reconfigures the debug pins.

    And, for such purposes, it should be in USER CODE BEGIN Init - immediately after HAL_Init():

     /* MCU Configuration--------------------------------------------------------*/
    
     /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
     HAL_Init();
    
     /* USER CODE BEGIN Init */
     <<<<< Here!
     /* USER CODE END Init */
    
     /* Configure the system clock */
     SystemClock_Config();

    Even in such cases, connecting under hardware reset should gain access.

     


    @vishnu_illikkal wrote:

    2. Put at the start of  /* USER CODE BEGIN 2 */ to give time to properly initialize DMA related functionality.


    Arbitrary delays are a band-aid fix at best.

    If a process needs time to complete, you should wait on some specific state/event which explicitly shows that it has finished.