2022-05-19 05:52 AM
Hello, First time using the forum so apologies if I mess something up...
Long story short I wanna get a microsecond delay, I know 2 ways of doing it:
1) I can start a timer with default cube values and use a function like:
void delay (uint16_t delay)
{
__HAL_TIM_SET_COUNTER(&htim1, 0);
while( __HAL_TIM_GET_COUNTER(&htim1) < delay);
}
to get the desired delay, or
2) I can start timer, set its prescaler value to specific frequency with interrupt turned on, drop it down to 1khz/mhz for easier calculations and in timer callback function have some variable increase by 1, then use it in different function as time measurement, something similar to this:
uint8_t counter;
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
counter++;
}
void main() {
while(){
if(counter==20){
// do smth
counter=0;
}
}
}
I have used both of these methods previously and know one is running in blocking mode, other in non-blocking mode. So that got me wondering, what other differences do they have, if blocking mode isn't an issue which one is more preferable to use, takes up less space, is more efficient and accurate? And is there another method even better than these two I can use?
Solved! Go to Solution.
2022-05-19 06:33 AM
The difference in time. ie dt = (TimeB - TimeA)
void delay (uint16_t delay)
{
uint16_t start = __HAL_TIM_GET_COUNTER(&htim1);
while((__HAL_TIM_GET_COUNTER(&htim1) - start) < delay);
}
This can be called from a 100 threads and will behaves more consistently than you resetting it to zero and thresholding against the up-count from there.
2022-05-19 06:10 AM
Having it delta a free-running counter would be more thread/interrupt safe.
Also works for time-outs.
Would avoid interrupting at high speed, and having software counts.
If using a timer with interrupts, have a list of events you are managing, so you aren't creating dozens of different methods for what is a single time-line problem.
2022-05-19 06:17 AM
Thank you for your response;
An odd follow-up question, "Having it delta" - is this (delta) a term I'm not familiar with or a typo?
2022-05-19 06:33 AM
The difference in time. ie dt = (TimeB - TimeA)
void delay (uint16_t delay)
{
uint16_t start = __HAL_TIM_GET_COUNTER(&htim1);
while((__HAL_TIM_GET_COUNTER(&htim1) - start) < delay);
}
This can be called from a 100 threads and will behaves more consistently than you resetting it to zero and thresholding against the up-count from there.
2022-05-19 06:45 AM
That was very informative, thanks.
2022-05-19 10:39 AM
Tesla's example has a bug - it will fail across overflow because of integer promotion. All of the operations will be done as an int type and therefore the subtraction will return a negative value. To correct that, the result must be cast to an unsigned type of the required size:
while((uint16_t)(__HAL_TIM_GET_COUNTER(&htim1) - start) < delay);