Reputation: 77
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
Upvotes: 0
Views: 7313
Reputation: 353
If you want to be able to delay by periods shorter than milli-seconds you can set up a timer to auto-reload and use the internal clock. The internal clock frequency set to the timer is shown in the cube MX clock tab. On my NUCLEO-F446RE most timers get 84MHz or 42MHz.
Timer 3 gets 42 MHz by default. So if I set the pre scaler to 42 and the count period to maximum (0xFFFF if 16 bit) I will have a cycling clock that changes every micro-second.
I can then, using a property of twos complement maths, simply subtract the old time from the new to get the period.
void wait_us (int16_t delay) {
int16_t t1= htim3.Instance->CNT;
while (( htim3.Instance->CNT - t1 ) < delay) {
asm ("\t nop");
}
}
This is an old trick from PIC18 C coding
Upvotes: 0
Reputation: 67855
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);
}
Upvotes: 3