Question
Best algorithm for calculating timer pre-scalar and period during run time?
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);