timing using millis () question

Hi everyone,

My desired output here is to read a switch and have pins 8 and 9 to output low, but after the switch is pressed for more than 5 seconds, pin 9 to output high.

I have viewed "how to do many things at once" and the blink W/O delay examples many times, however, I am still having trouble. I know I need a timer that starts when the switch is pressed. What I am running into is when I put (startTime) = to (currentTime) right after my switch is pressed,the code which turns my output to high after 5 seconds never initiates because my currentTime - startTime is always 0 due to the progression of the if statements.

Any help would be much appreciated!

const long interval = 5000;
unsigned long startTime = 0;

void setup() {
  //start serial connection
  Serial.begin(9600);
  //configure pin 2 as an input and enable the internal pull-up resistor
  pinMode(2, INPUT_PULLUP);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
}

void loop() {
  //read the pushbutton value into a variable
  int sensorVal1 = digitalRead(2);
  //print out the value of the pushbutton
  Serial.println(sensorVal1);

  unsigned long currentTime = millis(); // timer

  if (sensorVal1 == LOW) {
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    if (currentTime - startTime >= interval) {
      digitalWrite(9, HIGH);
    }
  }
  else {
    digitalWrite(8, HIGH);
    digitalWrite(9, HIGH);
  }
}

Do a search for ClickButton library and install and check out the examples.

It's an easy fix. You just forgot to update 'startTime' when it overflows.

aarg:
It's an easy fix. You just forgot to update 'startTime' when it overflows.

I think that is not quite correct.

The OP needs a line

startTime = millis();

when the switch changes from not-pressed to pressed. In other words the timing should start when the switch is first pressed

...R