微控制器中的定时器/预分频器

也许这是一个愚蠢的问题:

我有内部 20 MHz 振荡器、16 位定时器和预分频器(1、2、4、8、16、32、64、128),我想产生 1 毫秒的延迟。我知道怎么做 - (20 000 000 / 1) / 1000 = 20 000 -> 将此值放入 16 位寄存器,它就可以工作了。

使用预分频器 2 和 4,我得到相同的结果 1ms - (20 000 000 / 2) / 1000 = 10 000 和 (20 000 000 / 4) / 1000 = 5 000

我的问题是如何确定使用哪个预分频器?也许,我必须选择预分频器 4,因为这个值 (5000) 更接近 0,我的计时器从 0 开始计数到 ​​5000。如果我选​​择 10 000,计时器将计数 2 x 5000。

先感谢您 !

回答

当计数器在所需时间段内不够大时,您可以使用更高的预分频器。例如,如果您想要 10 毫秒的周期,则必须使用至少为4的预分频器才能获得 50000 的重新加载值。

导致重新加载小于 2 16的最小预分频器是您通常的目标。这为您提供了尽可能高的计数器分辨率,这对您将其用于 PWM 或输入捕获很有用。另一方面,如果您只是使用重新加载中断,这并不重要。

如果您需要的周期不是完全可以实现的,因为 in 不是时钟周期的精确倍数,那么使用较低的预分频器将最大限度地减少误差。

最后,如果你走得太低,你可能无法达到精确的时期。例如,对于您的 1ms 周期,64 的预分频器将导致重新加载 312.5,选择 312 会导致 ~1001.603ms 的周期或 313 的 ~998.403ms。

因此,通常重新加载值尽可能接近 65535 而不是您建议的零,这是您通常的目标。

  • Bear in mind one of the prescalers may affect other peripherals. In general it should only take a few minutes to write an ad-hoc program that goes through the combinations and searches out the one or ones that are the most accurate (same as you would for the baud rate divisor combinations for some MCUs), you may find and print out multiple combinations that have the same overall accuracy (digitally not counting the analog quality of the clock) and pick from those. If one of the divisor affects all peripherals you would certainly want to take that into account.
  • @TomServo True, but the question is about microcontrollers generally, not Arduino specifically. Apart from that best practice should be applied regardless, so that it becomes a habit for when it is critical. For example I work on applications requiring 2ppm TCXO, with synchronisation to GNSS 1PPS accurate to 60ns. You can laugh, but sometimes it matters. Moreover it is not simply a matter of "microseconds", it is a matter of drift. Even at 2ppm a TDMA radio application will fail to meet it's time slot sync requirements after less than a minute without GNSS synchronisation
  • @MetodiAngelov Yes. It is that simple. TomServo is right that it may make little difference, but that is not the point. One rule/guideline for all. Don't miss the main point though that the primary purpose of the prescaler in this case is to scale to allow the reload to fit the register.

以上是微控制器中的定时器/预分频器的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>