Timer / Prescaler in microcontrollers

Viewed 2697

Maybe it's a silly question:

I have internal 20 MHz oscillator, 16 bit timer and prescalers (1, 2, 4, 8, 16, 32, 64, 128) and I want to generate 1 ms delay. I know how to do that - (20 000 000 / 1) / 1000 = 20 000 -> put this value to 16 bit register and it works.

With prescalers 2 and 4, I have the same result 1ms - (20 000 000 / 2) / 1000 = 10 000 and (20 000 000 / 4) / 1000 = 5 000

My question is how to determine which prescaler to use ? Maybe, I have to choose prescaler 4, because this value (5000) is closer to 0 and my timer starts to count from 0 to 5000. If I choose 10 000, the timer will count 2 x 5000.

Thank you in advance !

2 Answers

You use a higher prescaler when the counter is otherwise not large enough for the period required. For example if you wanted a 10ms period, you would necessarily need to use a prescaler of at least 4 for a reload value of 50000.

The smallest prescaler that results a reload less than 216 is what you would normally aim for. That gives you the highest possible counter resolution which is useful of you are using it for say PWM or input-capture. If you are just using the reload interrupt on the other hand it is not critical.

If the period you need is not exactly achievable because in is not an exact multiple of the clock period, then using a lower prescaler will minimise the error.

Finally if you go too low, you may not be able to achieve the precise period. For example for your 1ms period, a prescaler of 64 would result in a reload of 312.5, choosing 312 results in a period of ~1001.603ms or 313 for ~998.403ms.

So generally a reload value as close as possible to 65535 rather than zero as you have suggested is what you you would generally aim for.

Mathematally it makes no difference which combination you choose.

The prescaler and the counter are both implemented in hardware and you won't see a performance impact.

However depending on your architecture your prescaler may run permanently and gives you an inaccuracy.

You should send the highest possible frequency (lowest prescaler, most precisest) into your timer/counter as possible.

Related