Search code examples
timerarmdelaystm32cortex-m

Implementing a delay using timers in STM32


Simply, I want to implement a delay function using stm32 timers, like the one in AVR microcontrollers "Normal mode". Can anybody help ? I just can't find that in the stm32 datasheet! It only supports PWM, input capture, output compare and one-pulse mode output! N.B: I forgot to mention that I'm using stm32F401 microcontroller


Solution

  • You have very special timer for this purpose called SysTick. Set it to overflow every 1ms. In its handler

    static volatile uint32_t counter;
    
    void SysTick_Handler(void)
    {
        counter++;
    }
    
    inline uint32_t __attribute__((always_inline)) GetCounter(void)
    {
        return counter;
    }
    
    void Dealy(uint32_t ms)
    {
      uint32_t tickstart = GetCounter();
    
      while((GetCounter() - tickstart) < ms);
    }