Push button with timer

Hi all :slight_smile:
I am new to Arduino environment and I would like to ask you for programming advise:
I am trying to do simple push button to switch on/off relay but if the button is pressed more than 5 sec to switch the relay off.

const int relay = A1; //relay
const int button = A0; //button
const unsigned long eventInterval = 5000;
unsigned long previousTime = 0;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
  pinMode(button, INPUT_PULLUP);

}

void loop() {
  //take current time
  unsigned long currentTime = millis();

  // run
  if (digitalRead (button) == LOW) {
    manualmode ();
    Serial.println(currentTime);
    previousTime = currentTime;//
    delay (10);
  }

  else {
    digitalWrite(relay, LOW);
  }

}

void manualmode () {
  //take current time
  unsigned long currentTime = millis();

  if (currentTime - previousTime >= eventInterval) {

    digitalWrite(relay, LOW);
    delay(1000);
  }
  else
  {
    digitalWrite(relay, HIGH);
  }

} //end run timer

My question is: How to update previousTime only once when i press the button.
or is there any other way to do it

Thank You for your suggestions.

How to update previousTime only once when i press the button.

You need to detect when the button becomes pressed rather than when it is pressed

See the StateChangeDetection example in the IDE

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