Recent

Author Topic: STM32 microseconds delay  (Read 3162 times)

funlw65

  • Full Member
  • ***
  • Posts: 148
    • 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. }

FreePascal 3.2.2, C 10.2.1, D 1.24 under Linux(init,musl,glibc), DragonflyBSD, NetBSD
gui: gtk2, qt5, raylib4.x+raygui3.x, nanovg 
tui: freevision, tvision2, termbox2+widgets, finalcut
db: typhoon-1.11...

MiR

  • Sr. Member
  • ****
  • Posts: 250
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: 148
    • 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.
FreePascal 3.2.2, C 10.2.1, D 1.24 under Linux(init,musl,glibc), DragonflyBSD, NetBSD
gui: gtk2, qt5, raylib4.x+raygui3.x, nanovg 
tui: freevision, tvision2, termbox2+widgets, finalcut
db: typhoon-1.11...

 

TinyPortal © 2005-2018