可以串行打印每个输出高电平的毫秒数。假设我编写了一个代码analogRead。如果模拟读数大于600,则数字写13,高。如果输出引脚13为高,则捕获多毫秒直到引脚13变为低。
我尝试过millis(),但它不能重置回零...有必要将millis()重置为零吗?
发布于 2015-07-23 21:48:15
您需要一个变量来跟踪事件之间的millis()计数,这有点像秒表:您需要记住开始计数,以便在停止计数时可以测量差异。
这里有一个快速的草图来说明这个想法。代码没有在Arduino上测试,但您应该能够从注释中理解其中的概念:
long lastTime;
int ledState = 0;
void setup() {
Serial.begin(115200);
pinMode(13,OUTPUT);
}
void loop() {
int analogValue = analogRead(0);
int newLedState = (analogValue > 600);//need to check, hoping boolean will evaluat to 1 when true
if(ledState == 0 && newLedState == 1){//if the led was of, but will be turned on, start the stop watch
lastTime = millis();//store the current time
ledState = newLedState;
}
if(ledState == 1 && newLedState == 0){//if the led was on, but will be turned off, get the difference between the last time we started counting time
long difference = millis() - lastTime; //get the current time, but subtract the last stored time
ledState = newLedState;
Serial.println(difference);
}
digitalWrite(13,ledState);
}发布于 2015-07-23 21:51:41
好的,我想我明白你想要什么了。您想要捕获2个引脚改变其电气状态之间的时间差。要做到这一点,您可以使用pulseIn()。
在你的问题中使用你的例子我们得到...
if (13 == HIGH) {
millis = pulseIn(13, LOW);
}这将给出引脚变高和变低之间的持续时间,存储在变量millis中。将其存储在long中是一种很好的做法。
https://stackoverflow.com/questions/31588337
复制相似问题