Close

Delays

A project log for Electronic Load 3.3V-16V 1A

Electronic load that supports 3.3V-16V at 1A of current. Equipped with keypad, LCD, rotary encoder, STM32 Microcontroller and more!

schwarzrmsuschwarzrmsu 12/13/2019 at 00:450 Comments

One of the first things I do in a SW project is identify the delay functions I wish to use, and test them.  I have not used and STM32 mico before, therefore I am going to test the performance of the HAL_Delay() function:

HAL_GPIO_WritePin(GPIOA, GPIO_PIN_9, GPIO_PIN_SET);
HAL_Delay(1000);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_9, GPIO_PIN_RESET);
HAL_Delay(1000);

I measured each delay pulse width using a scope at 1s, 100ms, 10ms, 5ms & 1ms.

1s:

100ms:

10ms:

5ms:

1ms:

At longer delays >100ms I really like the HAL_Delay() function.  At lower delays <10ms I noticed there is nearly a +1ms error that may add a significant amount of overall delay if used often.  Also there is no option to go into a microsecond time frame which will definitely be necessary when writing functions for the LCD.  When driving the LCD, every character write requires a 40us delay, but if using the HAL_Delay(1), it would cause the following overall delay:

This is a lot of delay for one type of feature, therefore I generated a micro second delay using an internal timer:

void delay_us(uint16_t delay){
    delay = delay * 48;
    __HAL_TIM_SET_COUNTER (&htim6, 0);
    while (__HAL_TIM_GET_COUNTER(&htim6) < delay);
}

This function takes an integer (number of microseconds) multiplies it by 48.  Then it resets timer 6, and timer 6 starts counting up at 48MHz.  Therefore the timer counts to 48 in 1us.  The while loop waits until it counts all the way up to the limit and then returns back to where the function was called.  I made the same measurements on my delay_us() function.

100us:

10us:

5us:

1us:

I am really happy with the delay_us() function.  Also I created a delay_ms function:

void delay_ms(uint16_t delay){
    while(delay > 0){
        delay_us(1000);
        delay = delay - 1;
    }
}

This function simply takes an integer, and runs through delay_us(1000) that number of times.  Pretty simple.  Below are the measurements results:

1s:

100ms:

10ms:

5ms:

1ms:

I am very happy with the accuracy of the delay_ms() function as well.  I can be confident how long certain delays should be now that I understand and have measured these delays.

Discussions