简体   繁体   English

没有引脚控制的Arduino定时器中断

[英]Arduino timer interrupt without pin control

Help me please with Arduino Timer Interrupts.请帮助我使用 Arduino 定时器中断。

How to start timer OCR0A or OCR2A without pin-controlling to start my custom function output1Display() ?如何在没有引脚控制的情况下启动计时器 OCR0A 或 OCR2A 来启动我的自定义函数output1Display() Interval of 1 ms.间隔 1 毫秒。

ATmega328P, 8MHz quartz. ATmega328P,8MHz 石英。

First of all, you should search for and download the 328P datasheet, which covers the details of timer setup.首先,您应该搜索并下载 328P 数据表,其中包含定时器设置的详细信息。 I suggest you use Timer2 only, since Timer0 is used for other things you probably don't want to mess up.我建议您只使用 Timer2,因为 Timer0 用于您可能不想搞砸的其他事情。

Since the datasheet can be confusing when you are starting out, here's what you need: First, you need to select a clock scaler.由于数据表在您刚开始时可能会令人困惑,因此您需要以下内容:首先,您需要选择时钟分频器。 Timer2 can count the main clock directly, or divided by 8, 32, 64, 128, 256, or 1024 for slower rates. Timer2 可以直接对主时钟进行计数,也可以对较慢的速率进行 8、32、64、128、256 或 1024 分频。 Note that Timer2 uses an 8-bit counter, so the slowest you can get (with a load of 255) is 256 ticks of the prescaled clock.请注意,Timer2 使用 8 位计数器,因此您可以获得的最慢(负载为 255)是预分频时钟的 256 个滴答声。 If you have an 8 MHz clock and want a timer interval of one msec, you can set the prescaler for 1/32 to get a counter clock of 250000 Hz, then load OCR2A with 249 to get a division by 250 for a 1000 Hz interrupt rate.如果你有一个 8 MHz 的时钟并且想要一个 1 毫秒的定时器间隔,你可以将预分频器设置为 1/32 以获得 250000 Hz 的计数器时钟,然后用 249 加载 OCR2A 以获得 1000 Hz 中断的 250 分频速度。 The Setup code looks like this:设置代码如下所示:

TCCR2A = 2;            // Set CTC mode.  Same as TCCR2A = _BV(WGM21);  
TCCR2B = 3;            // Prescaler to divide by 32 (CS21 and CS20 only)
TCNT2 = 0;             // Clear the counter
OCR2A = 249;           // Set for 1 msec rate
TIMSK2 = 2;            // Set OCIE2A to begin counting with Compare A

Your interrupt handler is declared like this, which should appear after Setup and before Loop:你的中断处理程序是这样声明的,它应该出现在 Setup 之后和 Loop 之前:

ISR(TIMER2_COMPA_vect)
{
// Your code goes here
}

Note that the timer can be set up in your main Loop on command from Serial if needed, such as if you don't want to start the interrupts until you have some other needed data.请注意,如果需要,可以在您的主循环中从串行命令中设置计时器,例如,如果您不想在获得其他所需数据之前启动中断。 Or you can leave all the setup as-is except for the final TIMSK2 = 2;或者您可以保留所有设置,除了最终的 TIMSK2 = 2; which can be given by your serial command,可以由您的串行命令给出,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM