How do I measure the total length of time an Arduino pin reads HIGH?

Hey guys,

Here is my code:

void setup() {
  
  Serial.begin(9600);
  pinMode(4, INPUT);
  pinMode(5, OUTPUT);

}

void loop() {

  if (digitalRead(4) == LOW) {
    digitalWrite(5, LOW);
  }
  else {
    digitalWrite(5, HIGH);
  }

}

Pin 4 will fluctuate between LOW and HIGH states, so pin 5 will fluctuate accordingly as well.
I need to track the total length of time that Pin 5 was set to HIGH during the duration of the program.

I read somewhere that I can do this by saving the start and end time that the input was HIGH, printing the time period when that input becomes LOW, and writing a variable to store the running total.

The problem is that I am very new to programming and don't know how to do that.

Any help will be much appreciated!

Karma for first post code tags.

A good starting point is to study and get an understanding of the first five demos in IDE -> file/examples/digital.

See also: Using millis() for timing beginner’s guide.

Try this and see if it works for you.

if ( digitalRead(5) == high && counting==false)
	starttime=millis();
	counting=true;
}


if (digitalRead(5) == low  && counting==true) {
     counting = false;
     elapsed_time = millis()- startime;
     total_time = total_time + elasped_time;
     elaspsed_time=0; 
}
1 Like

The code works! Thank you for helping me out

1 Like