Arduino TCNT1计算中断之间的时钟周期?

jtp*_*jtp 1 arduino

我是Arduino编程的新手,正在尝试将arduino uno用作高分辨率计时器。我希望能够在两个上升沿中断之间以完整的16MHz速率计数时钟周期。我有一些代码可以使用具有4微秒分辨率的micros()函数来工作,而我需要的更好。这是我尝试使用micros()进行计时的示例代码:

volatile int k = 0;
volatile float t1 = 0;
volatile float t2 = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(2), ISR1, RISING);
  attachInterrupt(digitalPinToInterrupt(3), ISR2, RISING);
}

void ISR2()
{
  k = 1;
  t1 = micros();
  Serial.println(1);
}

void ISR1()
{
  k = 2;
  t2 = micros();
  Serial.println(2);
}

void loop()
{
  if (t1 != 0 && t2 != 0) {
    if (t2 - t1 < 0) {
      t1 = 0;
      t2 = 0;
    }
    else {
      Serial.print("tdelta ");
      Serial.print(t2 - t1);
      t1 = 0;
      t2 = 0;
      Serial.println(0);
    }

    }
}
Run Code Online (Sandbox Code Playgroud)

我意识到我的micros时序可能会因中断而有所偏移,这可能是个问题。

谁能指出我正确的方向?

我想使用Timer1,因为它是16位的,并且我的事件应该足够快才能在发生任何溢出之前完成。我希望找到一种简单的方法,将第一个中断的tcnt1设置为0,然后计数tcnt1时钟周期直到第二个中断。我什至不知道如何从tcnt1读取值,所以我有一条路要走。

我已经搜索了示例,但还没有真正找到合适的示例。一切似乎都针对定时器中断,我认为这并不是我想要的。

我可能缺少使用此tcnt1计数器所需的很多知识,但是对我指明正确方向的任何帮助将不胜感激!

谢谢

Vla*_*nov 5

您可以尝试直接使用计时器寄存器。请参阅您的特定板上使用的CPU手册。对于mega,它是ATmega2560-16AU。定时器寄存器的名称为TCNT1。您可以存储其值:

int t1;// declare global variable somewhere
t1 = TCNT1; //save timer value in ISRx interrupts
Run Code Online (Sandbox Code Playgroud)

确保设置预分频器值TCCR1B.CSn并处理定时器溢出中断,否则将丢失时间数据:ISR(TIMER1_OVF_vect)

如您在这里所读,可以达到<1 usS的精度。 有关如何直接使用CPU定时器寄存器的更多信息