Arduino上的脉冲计数器

Pulse Counter on Arduino

本文关键字:脉冲计 计数器 脉冲 Arduino      更新时间:2023-10-16

我需要一个函数,在arduino上返回指定时间内的脉冲数。这是我使用的部分代码,但函数不返回任何东西(甚至不返回0)

long Itime = 0;
int Dtime = 25;

int Counter() {
    unsigned long Ftime = millis();
    int c = 0;
    int i = 0;
    while ( Ftime - Itime < Dtime ) {
        if ( digitalRead(PSPin) == HIGH ) {
            i=i+1;
            while ( digitalRead(PSPin) == HIGH) { // delays the function until
                c=c+1;                        // the next cycle
                c=c-1;
            }   
        }
    }
    Itime = Ftime;
    return i;
    }

我真的不明白为什么函数不返回' I '。如果有人能帮忙我会很高兴。由于

编辑:PSPin上的信号是一个150hz的正方形信号,这意味着周期大约是6ms,因为我的时间是25ms,它应该返回至少3个脉冲。我调用这个函数只是为了测试的目的,因为我也认为我的程序在Counter()函数上卡住了,但我不知道为什么。

void loop() {
     if ( Counter() == 0 )
     digitalWrite(TestPinA, HIGH);
     if ( Counter() > 0 )
     digitalWrite(TestPinB, HIGH);
     }

但是两个引脚都不会返回HIGH。非常感谢您的帮助。

你被卡住了

while ( Ftime - Itime < Dtime )

,因为在while循环中,代码实际上从未更新过Ftime或Dtime。试试以下命令:

int PSPin = 13;
int DurationTime = 25; // best to have same type as compare or cast it later, below.
int Counter() {
    int i = 0;
    unsigned long StartTime = millis();
    unsigned long PrvTime = StartTime ;
    while ( PrvTime - StartTime < (unsigned long) DurationTime ) {
        if ( digitalRead(PSPin) == HIGH ) {
            i=i+1;
            while ( digitalRead(PSPin) == HIGH); // BLOCK the function until cycles
        }
        PrvTime = millis();
    }
    return i;
}

使用中断使工作更容易。

volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2
void setup() {
  // put your setup code here, to run once:
attachInterrupt(pin_irq, IRQcounter, RISING);
delay(25);
detachInterrupt(pin);
Serial.print(F("Counted = ");
Serial.println(IRQcount);
}
void IRQcounter() {
  IRQcount++;
}
void loop() {
  // put your main code here, to run repeatedly:
}

如果您想使用INT0/1以外的引脚。您可以使用PinChangeInt library来使用任何引脚