【发布时间】:2013-10-13 11:32:38
【问题描述】:
我正在尝试使用 Teensy 2.0 微控制器(基于 ATMEGA32U4 8 位 AVR 16 MHz)设置两个定时器中断例程,以独立控制两个伺服电机
经过多次尝试 - 我能够在端口 C 的引脚 7 上设置一个,但是
- 如何设置第二个 ISR 以独立于第一个 ISR 进行初始化和调用?
- 我是否需要设置第二个计时器,如果需要,这样的代码应该是什么样的?
这里是设置代码:
int main(void)
{
DDRE = 0xFF;
TCCR1A |= 1 << WGM12; // Configure timer 1 for CTC mode
TCCR1B = (1<<WGM12) | (1<<CS11) ;
OCR1A = 1000; // initial
TIMSK1 |= 1 << OCIE1A; // Output Compare A Match Interrupt Enable
sei(); // enable interrupts
// ...code that sets pulseWidth based on app logic variable.
// Not showing as its not important
}
ISR(TIMER1_COMPA_vect)
{
if (0 == pulseWidth)
{
return;
}
static uint8_t state = 0;
int dutyTotal = 20*1000;
if (0 == state)
{
PORTC |= 0b10000000;
OCR1A = pulseWidth;
state = 1;
}
else if (1 == state)
{
PORTC &= 0b01111111;
OCR1A = dutyTotal - pulseWidth;
state = 0;
}
}
【问题讨论】:
-
你想达到什么目的?你不能在同一个 ISR 中实现第二个电机的逻辑吗?看来您只想为每个电机输出一个 PWM。
-
由于电机需要独立控制,我不确定如何从同一个 IRS 进行操作,因为定时器会根据电机的需要在 ISR 中触发,所以它会当其他电机需要它时不要点火。也许我错过了一些东西。我想我可以将计时器设置为总是每隔 100 微秒触发一次,然后为独立端口实现逻辑,你的意思是?
-
是的,这就是我的意思。将一个时间设置为多个任务的时间基准并不少见。选择适当的频率。您必须注意 ISR 的代码执行时间永远不会超过 ISR 间隔,否则您将跳过中断并获得不规则的时序。