Measure time that a condition is true to then trigger and action

Please look at the below example,

#define buttonPin 12
#define ledPin  13

#define DEBOUNCE_PERIOD 10    // 10 milliseconds
#define TIME_DELAY      3000  // 3000 milliseconds

enum state_t : bool {STOP, START};

bool enable;
unsigned long startTime;
unsigned long currTime;

void setup() {
  Serial.begin(115200);
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  Serial.println("Press the PB!");
}

void loop() {
  if (enable) {
    currTime = millis();
    if (currTime - startTime >= TIME_DELAY) {
      enable = false;
      Action(STOP);
    }
  } else {
    if (isPressed()) {
      startTime = millis();
      enable = true;
      Action(START);
    }
  }
}

void Action(state_t value) {
  switch (value) {
    case START:
      digitalWrite(ledPin, HIGH);

      Serial.println("Delay Time:\t" + String(TIME_DELAY) + " milliseconds.");
      break;

    default:  // case STOP:
      digitalWrite(ledPin, LOW);

      Serial.println("Elapsed Time:\t" + String(currTime - startTime) + " milliseconds.\n");
      Serial.println("Press the PB!");
      break;
  }
}

bool isPressed() {
  static bool buttonState;
  static bool input;
  static unsigned long startDebounceTime;

  bool prevInput = input;
  input = digitalRead(buttonPin);

  if (input != prevInput) {
    startDebounceTime = millis();
  }

  if (input != buttonState) {
    if (millis() - startDebounceTime >= DEBOUNCE_PERIOD) {
      buttonState = input;
      return buttonState == LOW;  // When pressed, state = LOW if pin mode = INPUT_PULLUP, and state = HIGH if pin mode = INPUT.
    }
  }
  return LOW;
}

Did.

The LED stays on as long as the button is pressed, and then long enough so that the total on time is N * TIME_DELAY.

Or does it?



No! The LED is repeatedly launched for an additional period of TIME_DELAY after briefly (578 microseconds) turning off.

I suggest adding state change detection. You may need debouncing.

a7

1 Like

Thank you for your suggestion. The sketch has been updated at post #22.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.