Electronic – STM32F103 simple countdown timer (with no interrupts)

stm32stm32f10x

I'm trying to create a simple countdown timer (without using interrupts) – to use to check for timeout while waiting for an external event to occur.

Ideally, I'd like to preload a timer counter with a specific value and have it count down and stop once it gets to zero – so that I can poll for a zero counter value in my while loop.

I'm struggling to get the timer to run, and none of the examples I can see in the reference manual is this simple.

Can anyone point me towards a simple example of a one shot countdown timer implementation?

Best Answer

After some investigation, it seems like I can't have a down counter which stops at zero without using interrupts (as far as I can discover). It also seems that down counters are not possible unless I'm running in centre-aligned or encoder mode.

As a result, I've gone for the following implementation, which uses an up-counter. It seems to work fine, although I'm slightly nervous that the counter has the slight possibility to automatically reload before my while loop has seen that it has gone over the threshold - but as long as my check value is well below the automatic reload value I should be fine.

There may be better ways to do this.

/* Set timer prescaler (0 = no divide - clk = 8MHz) */
TIM2->PSC = 0;

/* Set reload register well above the longest time that we're interested in */
TIM2->ARR = 0xFFFF;

/* Enable the timer */
TIM2->CR1 |= TIM_CR1_CEN;

/* Wait for 1ms */
TIM2->CNT = 0u;
while (TIM2->CNT < 8000u) {}