Timeout code help needed

Hi all, I am in the process of programming a board and I am stuck on the last hurdle.
i need a piece of code to watch and input and if it goes LOW for 300Sec, if it does then I need it to do a command.

I have the command part sorted but at the moment I am using some debounce script and its not working how I want it to.

what code does everyone suggest?
IF pin2 = low (300Sec) THEN ... is all I need but im getting stuck now :frowning:

if you have any suggestions please let me know.

perhaps something along these line will help. Your sketch would need to call pinTime each time through the loop to check the state. You can modify the code to use an interrupt but be careful that your command does not consume too much time

int inPin = 2;

// setup code here...

void loop() {
// your existing code here:
if(pinTime() > 300000)
// do your command
}

// declare inPin as pin 2  earlier in your sketch 

// return the time in milliseconds that the inPin is low
long pinTime()
{
  static unsigned long startTime = 0;  // the time the pin state change was first detected
  static boolean state;                // the current state of the pin

  if(digitalRead(inPin) != state) // check to see if the pin has changed state
  {
    state = ! state;       // yes, invert the state
    startTime = millis();  // store the time
  }
  if( state == LOW)
    return millis() - startTime;   // pin is low, return the time in milliseconds   
  else
    return 0; // return 0 if the pin is high;   
}

that looks like a good way to do it.
another way that i was pondering was:
the resulting action only happens if the pin does not go high for 300 Sec
so...
is there a piece of code that sees the pin go high and start a counter, each subsequent time the pin goes high it resets the counter to Zero.
If the counter reaches 300 then the resulting action will result.
i.e.
if input pin = high then reset counter
if counter = 300 then do action.

or would this use more rescource?

the resulting action only happens if the pin does not go high for 300 Sec

If the pin does not go high it must be low. The pin not going high for 300 seconds is the same as the pin being low for 300 seconds, and that is what the posted code checks.

The counter is reset every time the state changes (goes from low to high or high to low). This makes it easy to modify to code to return the HIGH duration if that was needed in another application. But as posted, the time returned is the total time it has been LOW (not HIGH) if it is currently LOW

I hope that helps