Recent

Author Topic: STM32 microseconds delay  (Read 2098 times)

funlw65

  • Full Member
  • ***
  • Posts: 116
    • Visual Pin Configurator for Nucleo 64pin boards
STM32 microseconds delay
« on: March 08, 2021, 04:38:54 pm »
I'm aware that if you need microseconds timing precision, STM32L1 is not a good bet. For that matter, is better to use an 8bit/16bit micro and interface it with I2C or SPI. Onewire protocol is one example where you need good timing for the thing to work.

Still, I have a delay function in assembler that is good enough for such a case, it works well when I use it with HAL/LL driver no matter the level of optimization in the gcc compiler, but it needs some tweaking if I use it with SPL driver and it depends on the optimization level. If optimization is disabled, if I use SPL, I can't make it work. Worse, I do not posses an oscilloscope. As I understand, freepascal do not optimize for ARM yet...

Anyway, I need help to write this function in freepascal, can anyone know how to do it? Thank you, whatever the outcome!

Code: C  [Select][+][-]
  1. static __INLINE void my_delay_us(uint32_t us)
  2. {
  3.   us *= 24; // it was 32
  4.   us--;
  5.   asm volatile("   mov r0, %[us]\n\t"
  6.                "1: subs r0, #5\n\t"
  7.                "   bhi 1b\n\t"
  8.                :
  9.                : [us] "r" (us)
  10.                : "r0");
  11. }

Lazarus 2.2.0rc3 fpc 3.2.2, Linux, UNIX BSD
widgetset: gtk2, msegui, qt5,  bgrabitmap controls
Immediate mode GUI: raygui 3.0

MiR

  • Full Member
  • ***
  • Posts: 225
Re: STM32 microseconds delay
« Reply #1 on: March 08, 2021, 05:21:58 pm »
The best solution is to read the chapter about timers in the reference manual of your chip.
When you know the operating frequency of your chip you can get very good results for complex timing requirements.

Another good option is to use the cycle counter of cortex-m chips, a quick google query brought up this page:

https://github.com/keatis/dwt_delay/blob/master/dwt_delay.c

which shows the idea...

you will have to include cortexm3.pp in your code to get the DWT Registers resolved.
« Last Edit: March 08, 2021, 05:25:08 pm by MiR »

funlw65

  • Full Member
  • ***
  • Posts: 116
    • Visual Pin Configurator for Nucleo 64pin boards
Re: STM32 microseconds delay
« Reply #2 on: March 08, 2021, 06:26:53 pm »
Last time I tried DWT it was a fail, obviously my fault. Thank you for the link, I will try that, first in C as I really needed a good, reliable solution, then in freepascal.
Lazarus 2.2.0rc3 fpc 3.2.2, Linux, UNIX BSD
widgetset: gtk2, msegui, qt5,  bgrabitmap controls
Immediate mode GUI: raygui 3.0

 

TinyPortal © 2005-2018