Arduino上的脉冲计数器
Pulse Counter on Arduino
我需要一个函数,在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来使用任何引脚
相关文章:
- 计算数组c++的平均值
- 循环在计数器中不起作用
- python集合的C++等价物是什么.计数器
- Python 集合.计数器,如何避免重复查找
- 请解释字谜的代码,我看不懂计数器数组,每个值已经是0
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- std::shared_ptr 自定义参考计数器
- 英特尔 TBB 程序不会终止,可能会误用参考计数器
- 将 IPv6 支持添加到雨量计
- 不正确的比较和交换计数器输出用于快速排序功能
- OpenSSL API,使用GCM(伽罗瓦计数器模式)进行AES加密
- C++ 在循环中添加计数器变量并再次初始化其值
- 需要帮助才能在C++中创建类计数器
- 漂亮的计数器习语的错误或格式错误的静态订单惨败?
- 几乎总是自动和带计数器的循环
- 线程使用计数器C++
- 为什么使用 2 个嵌套循环 O(n^2) 复杂度来解决二和问题,当只改变循环计数器逻辑时运行得更快?
- 对于循环计数器不递增
- C++输出的就地计数器
- Arduino上的脉冲计数器