Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer / prescaler in microcontrollers

I have an internal 20 MHz oscillator, a 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

How can I 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.

like image 562
Metodi Angelov Avatar asked May 01 '26 09:05

Metodi Angelov


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 10-ms 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 it 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 1-ms period, a prescaler of 64 would result in a reload of 312.5, choosing 312 results in a period of approximately 1001.603 ms or 313 for approximately 998.403 ms.

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

like image 68
Clifford Avatar answered May 04 '26 18:05

Clifford


Mathematically, it doesn't make any 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 give you an inaccuracy.

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

like image 42
user5329483 Avatar answered May 04 '26 18:05

user5329483



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!