cancel
Showing results for 
Search instead for 
Did you mean: 

Best algorithm for calculating timer pre-scalar and period during run time?

arnold_w
Senior
Posted on June 16, 2016 at 15:16

I am working with the Discovery Development Board (STM32F407) and I would like to have functions for the 16-bit timers that looks like this:

void
startTimer(uint32_t timeoutMs, EventCallback_t timerInterruptCallback)

I'm currently using the formula below, but I recently discovered and corrected an overflow problem that makes this algorithm pretty bad (the error is less than 1% for timeout values below 800 ms at 32 MHz timer clock, but above that it gets pretty bad). I don't want to use floating point mathematical operations or lookup tables. Does anyone have any clever ideas?

clockFreqBeforeDivision = GET_TIMER_FREQ(TIM2);
perfectClockFreqAfterDivision = (((uint32_t)(1000 * 65536)) / ((uint32_t)milliseconds));
divisor = 1 + (clockFreqBeforeDivision / perfectClockFreqAfterDivision);
actualClockFreqAfterDivision = clockFreqBeforeDivision / divisor;
timerPeriod = milliseconds * (actualClockFreqAfterDivision / 1000);

4 REPLIES 4
Posted on June 16, 2016 at 16:34

Does anyone have any clever ideas?

Here's a paradigm shifting thought, TIM2 is 32-bit, drive it as a high frequency, free running time base, with a maximal count and set the timeout interrupt by programming the TIM2->CCRx X milliseconds ahead of  current TIM2->CNT

At 72 MHz the wrap time is about a minute, right? At 1 MHz you'd have over an hour range.

For period/prescaler stuff you are factoring into two integers, generally you'd want the prescaler to be the smaller of the two, as you want the period to be more that 1 or 2

Tips, buy me a coffee, or three.. PayPal Venmo Up vote any posts that you find helpful, it shows what's working..
arnold_w
Senior
Posted on June 16, 2016 at 19:28

I estimate that I will need at least 8 timers so I must use some 16-bit timers. 

Posted on June 16, 2016 at 21:34

Each timer has 4 channels, you could also manage a list of upcoming events and sequence them.

People often manage a long list of events and hand-off during the 1KHz (1ms) ticker as each expires.

Tips, buy me a coffee, or three.. PayPal Venmo Up vote any posts that you find helpful, it shows what's working..
arnold_w
Senior
Posted on July 12, 2016 at 13:07

The original post was too long to process during our migration. Please click on the provided URL to read the original post. https://st--c.eu10.content.force.com/sfc/dist/version/download/?oid=00Db0000000YtG6&ids=0680X000006I6jN&d=%2Fa%2F0X0000000bu8%2Fh5UHzCuNc.SEnMqE7EhSiIj.AE1IY5cpuz3oxnKMFI8&asPdf=false