Arduino定时器2中断和程序触发

时间:2014-01-21 16:22:38

标签: arduino atmega

我正在使用Arduino Mega2560,我在标志溢出2ms后使用timer2作为中断,但不知何故它只能工作一次。我已经使用了串行监视,你也可以看到,这告诉我调用了定时器中断但是没有再次调用中断,程序控制也不会回到循环中,因为它只显示“13”和“22”一次。在调用定时器中断后,至少它应该连续显示“22”。任何人都可以告诉我为什么定时器中断不再被调用以及为什么它在中断后不会返回循环。?

#include <avr/io.h>
#include <avr/interrupt.h>

int eraser=0;             //0=000

ISR(TIMER2_OVF_vect)
{
  TIMSK2=0x00;
  TCCR2B=0x00;
  TCCR2A=0x00;
  TCNT2=0;
  TIFR2=0x00;
  Serial.println(33);

  TCNT2= 131;         //reset timer count to 125 out of 255. 
  TCCR2B=0x6;     //using a prescaler of 6 to use divisor 256.
  TIMSK2=1;      //timer2 Interrupt Mask Register. Set TOIE(Timer Overflow Interrupt Enable).
}


void setup()
{
  /*Timer0 would not be used as it is used for other functions.
    Timer 5(pin D47) for encoder and interrupt 2(pin 21) for encoder.
    Timer2 is 8 bit we'll see if it can be used for time interval between two encoder counts.
    This leaves us with Timers 1,3,4,5.
    Timer 3(5,3,2) and 4(8,7,6) will be used for motors.*/

  Serial.begin(9600);

  TCCR2B&=eraser;
  TCNT2= 131;         //reset timer count to 125 out of 255.
  TIFR2= 0x00;      //timer2 interrupt flag register: Clear Timer Overflow Flag. 
  TIMSK2=0x01;      //timer2 Interrupt Mask Register. Set TOIE(Timer Overflow Interrupt Enable).
  TCCR2B=0x6;     //using a prescaler of 6 to use divisor 256.
  /*
  so it takes 62.5ns per tick in a timer and having set 
  divisor of 256 so it will take 16usecs per inc and setting 
  timer2 to 125 would make it count 250 times so 
  time=62.5nsec * 256 * 125=2msec. 
  clkTn
  TCNTn Timer Counter Register
  TCCRnA has LSB of WGM(wave generation mode bits)
  TCCRnB Timer Counter Control Register: has LSB of CSn2,CSn1,CSn0.*/ 

}

void loop()
{ 

  Serial.println(1);
  while(1)
  {

     Serial.println(22);
  }
}

1 个答案:

答案 0 :(得分:0)

您是否尝试过

ISR(TIMER2_OVF_vect)
{
  TIMSK2=0x00;
  TCCR2B=0x00;
  TCCR2A=0x00;
  TCNT2=0;
  TIFR2=0x00;
  Serial.println(33);

  TCNT2= 131;         //reset timer count to 125 out of 255. 
  TCCR2B=0x6;     //using a prescaler of 6 to use divisor 256.
  TIMSK2=1;      //timer2 Interrupt Mask Register. Set TOIE(Timer Overflow Interrupt Enable).
}

阻止并将其中的部分或全部放入您想再次启动计时器的位置?

setup只运行一次,所以我猜你需要再次启动计时器。