【问题标题】:How to capture millisecond in arduino如何在arduino中捕获毫秒
【发布时间】:2015-07-23 13:09:45
【问题描述】:

可以串行打印每个输出高的毫秒数。假设我写了一个代码analogRead。如果analogread 大于600,则digitalwrite 13,高。如果输出引脚 13 为高电平,则捕获引脚 13 变为低电平之前的毫秒数。

我尝试使用millis(),但它无法重置为零...无论如何要将millis() 重置为零?

【问题讨论】:

    标签: arduino


    【解决方案1】:

    您需要一个变量来跟踪事件之间的 millis() 计数,有点像秒表:您需要记住您开始计数,以便在停止时测量差异。

    这里有一个简单的草图来说明这个想法。代码未在 Arduino 上测试,但您应该能够从 cmets 中理解这个概念:

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

    【讨论】:

      【解决方案2】:

      好的,我想我明白你在这里想要什么。您想捕捉 2 个引脚改变其电气状态的时间差。为此,您可以使用pulseIn()

      在您的问题中使用您的示例,我们得到...

      if (13 == HIGH) {
      millis = pulseIn(13, LOW);
      }
      

      这将为您提供引脚从高电平到低电平之间的持续时间,存储在变量毫秒中。长期保存是个好习惯。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多