【问题标题】:Pulse Counter on ArduinoArduino上的脉冲计数器
【发布时间】:2014-03-15 06:15:48
【问题描述】:

我需要一个函数,它在 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);
     }

但两个引脚都不会返回高电平。 非常感谢您的帮助。

【问题讨论】:

  • 我想“没有返回任何东西”意味着程序卡在Counter 函数中。它不会返回,因为Ftime - Itime &lt; Dtime 在第一时间永远不会为真,或者更有可能是因为digitalRead(PSPin) 总是返回HIGH
  • 怎么不返回anything?您必须以某种方式调用它,例如count = Counter(),那么调用后count(或您使用的任何变量)的值是多少?也许你应该在调用函数的地方显示代码。
  • 我刚刚编辑了我的帖子。我也认为这是问题所在,它卡在功能上,但我不知道为什么。

标签: c++ arduino


【解决方案1】:

你被困在了

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;
}

【讨论】:

  • 谢谢!!我是新手,所以我遇到了一些简单的错误。非常感谢您的帮助!
【解决方案2】:

使用中断来简化工作。

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 Libray 来使用任何引脚。

【讨论】:

  • 谢谢。这是做我想做的事的好方法。我会试试看..但我现在仍然想知道为什么我的功能是错误的..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-27
  • 2010-12-06
相关资源
最近更新 更多