0

I would like to produce an output after a constant input is detected for a certain amount of time. Below is a simple code of what I am trying to do minus the time factor. Can someone help me on how to code out the duration of an input occurrence? i.e.

if (sensorValue > threshold);
    //if this occurs for more than 4 hours, then
    digitalWrite (3, HIGH);
1
  • 3
    A constant input would be an analog value between two bounderies. Not just a check if it is above a threshold. Use millis for timing, it can count up to 50 days. The blink-without-delay uses an interval, but it explains the use of millis: arduino.cc/en/Tutorial/BlinkWithoutDelay Provide a minimal but complete working sketch please.
    – Jot
    Commented Mar 23, 2018 at 20:38

1 Answer 1

0

You must store the state of the last readings and do something like this:

    //Off-loop:
    bool state_changed = false;
    unsigned long time_in_state = 0;
    unsigned long last_reading = 0;

    //On-loop:
    if (sensorValue > treshold && !state_changed) {
        time_in_state += millis() - last_reading;
        last_reading = millis();
    }
    else {
        state_changed = true;
        time_in_state = 0;
    }

    if (time_in_state > TIME_REQUIRED) {
      digitalWrite (3, HIGH);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.