Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

Time between two High state of an input Arduino

I'm trying to make a program in Arduino Uno which can calculate the time interval (in mills) between two HIGH states of the same input .

int V1;

long int time1;
long int time2;
long int interval1;
long int lastvalue;

void setup (){
  pinMode(2, INPUT);
  Serial.begin(9600);
}
 void loop() {
  V1 = digitalRead(2); // reading state of input 2

  if (V1 ==HIGH) {
    Serial.print("Event occure: ");
    time1 = millis();
    Serial.print(time1);
    delay(500);
    
    interval1= time1 - lastvalue;
    Serial.print("difference between previous time1 and current time1 (in mills): ");
    Serial.print(interval1);
    
  }
 }

Can you give me a hint about how to calculate the difference between current value of time1 and last value (current time1-1) of time1?

Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do something like this.

unsigned long lastTime = 0;
int lastVal = HIGH;
int val = LOW;

void setup (){
  pinMode(2, INPUT);
}

void loop() {
  // read the current input value
  val = digitalRead(2);
  // if the value has changed since last time and is HIGH
  if(val != lastVal && val){

    // get current time
    unsigned long currTime = millis();
    // calculate difference to last time
    unsigned long timeDiff = currTime - lastTime;
    // get a new lastTime for next high
    lastTime = currTime;
    }
    // update lastVal so we know the input changed
    lastVal = val;  
 }

Alternatively you could use an interrupt with a rising edge in a similar fashion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...