1
\$\begingroup\$

I need to create 100 microseconds delay for STM32L0 using HAL. I have HSE 12 MHz. APB1 timer clocks 12MHz.

htim6.Instance = TIM6;
htim6.Init.Prescaler = 1199;
htim6.Init.CounterMode = TIM_COUNTERMODE_UP;
htim6.Init.Period = 1;

When I have a loop of 50000 iterations which wraps calls to polling start/stop basic TIM6 timer (HAL_TIM_Base_Start), then I have 10 seconds delay instead of 5 seconds (The outer loop serves just for time scaling). Is it normal? I've expected 50000 * 100 microseconds = 5 seconds. Should I use another timer? I need +-10 microseconds delta. By the way, STM32L0 HAL does not contain "microseconds version" of HAL_delay.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You are adding 50,000 iterations which contain a check, and increase for a counter. If this would take e.g. 5 clock cycli per iteration, this results is 250,000 cycli. With a 12 MHz clock this is 20,8 ms, which is anyway above your requirement.

I don't see the 5 seconds extra delay, but even 20,8 ms is too much. It might be related to stack handling if you call a separate function, still than 5 seconds is a lot, but it will be (much) longer than 20,8 ms.

The solution would be to put the right value directly in the timer prescaler/period and remove the counter/loop.

\$\endgroup\$
3
  • \$\begingroup\$ One more experiment has been done: when I set htim6.Init.Prescaler = 119; and htim6.Init.Period = 10; with 50000 iterations, then I got ~5 seconds delay. So, 10 steps with 10 microseconds were better than one 100 microseconds step \$\endgroup\$
    – ilya
    Dec 22, 2017 at 6:06
  • \$\begingroup\$ Outer loop was just for scaling, just to ensure that we have correct prescaler and period for such tiny delays. I've measured LED ON duration. By the way, should I decrease period by 1 for HAL struct? \$\endgroup\$
    – ilya
    Dec 22, 2017 at 6:14
  • \$\begingroup\$ I saw examples where indeed 1 was decreased from the maximum amount of loops... maybe to compensate for the overhead of the function call/return. \$\endgroup\$ Dec 22, 2017 at 14:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.