2023-12-15 05:42 AM
Hello guys.
I am working with STM32G030 MCU for delay in millisecond
HAL_Delay();
is working fine.
but I want to do a delay in microseconds
so will you please guide how I can do this?
I followed this tutorial but not getting desired result.
https://controllerstech.com/create-1-microsecond-delay-stm32
MY MCU operates on 16MHZ
Solved! Go to Solution.
2023-12-15 07:56 AM
Set up a 32-bit timer to count at 16 MHz. Then your delay function would look like this:
void DelayUS(uint32_t us) {
uint32_t start = TIMx->CNT;
uint32_t duration = us * 16;
while (TIMx->CNT - start < duration);
}
The delay will not be exactly 1 us due to overhead, but it will be close. You can get fancy and remove the overhead in the "duration" if desired, but be aware overhead will be dependent on compiler settings.
2023-12-15 07:56 AM
Set up a 32-bit timer to count at 16 MHz. Then your delay function would look like this:
void DelayUS(uint32_t us) {
uint32_t start = TIMx->CNT;
uint32_t duration = us * 16;
while (TIMx->CNT - start < duration);
}
The delay will not be exactly 1 us due to overhead, but it will be close. You can get fancy and remove the overhead in the "duration" if desired, but be aware overhead will be dependent on compiler settings.
2023-12-15 10:24 AM
Or a 16-bit one if there are no 32-bit TIM or your given 32-bit STM32
void DelayUS(uint16_t us) {
uint16_t start = TIMx->CNT;
uint16_t duration = us * 16;
while((TIMx->CNT - start) < duration);
}
You could also prescale to 1 MHz if thats easier, but the granularity is rougher.
You want the TIM to be maximal, and not interrupting. So TIM->ARR = 0xFFFF or 0xFFFFFFFF
2023-12-15 08:05 PM - edited 2023-12-15 08:08 PM
Don't forget the cast. The code will not fail in this particular case if the register type is uint32_t, but can easily turn into a bug if the register is replaced with a variable of a less than 32-bit size.
while((uint16_t)(TIMx->CNT - start) < duration);