使用 Arduino 测量频率

Measuring frequency with Arduino

本文关键字:频率 测量 Arduino 使用      更新时间:2023-10-16

我正在做一个使用 Arduino 测量输入方波频率的小项目,我使用定时器和硬件中断都做到了,这是我的代码:

#include <TimerOne.h>
long count1=0,freq1=0;
void setup(){
    attachInterrupt(5,count,RISING);
    Timer1.initialize(1000000); //increments count for 1 sec and prints out count
    Timer1.attachInterrupt( freq ); // attach the service routine here
    Serial.begin(9600);
}
void loop(){
    while(freq1)
        Serial.println(freq1);
}
void count()
{
    count1++; 
}
void freq(){
    freq1 =  count1;
    count1=0;
}

问题是输出值几乎是输入频率的两倍,我不知道这是怎么回事。我在密集的谷歌搜索后了解到中断。似乎没有用。

这里有

一个工作的例子。它使用本机ISR函数(更快)而不是arduino中断处理程序。使用 Timer1 获得最佳分辨率和精度。

代码很大,但您感兴趣的部分是:

The "// Setup Timer1 for precise timing" portion of void setup()
ISR(TIMER1_OVF_vect) -> for timer1 overflow counter
ISR(INT0_vect) // External Interrupt pin 2 [D2]
void PulseCaptureScheduler_callback()  // Starts a capture and flags a timeout
void PrintInfoScheduler_callback() // Processes the results