Millis() Problem

hello, I write this code and it doesn’t work correctly. I don’t know why? I want when I press the button, led turns on after (for example) 5 sec. but if I power on arduino and after 20 sec press the button, led turns on immediately. could you help me.

code:

#include <Bounce2.h>

#define ls1 3



#define yellow 5    //LED yellow


unsigned long timecurrent;
unsigned long timeccw = 5000;
unsigned long timepccw = 0;

int ccw = 0;

Bounce debouncer1 = Bounce(); 

void setup() {

  pinMode(ls1,INPUT_PULLUP);
  debouncer1.attach(ls1);
  debouncer1.interval(5);

  pinMode(yellow, OUTPUT);

  
  
}

void loop() {

  timecurrent = millis();

  
  debouncer1.update();


  if (debouncer1.fell()){
    ccw = 1;
    }
  if (ccw == 1){ 
    if (timecurrent - timepccw >= timeccw){
      timepccw = timecurrent;
      digitalWrite(yellow, HIGH);
    }
  }

}

You need to set timepccw to millis() when the button is pressed. The way your code is currently written, this line:

    if (timecurrent - timepccw >= timeccw){

Is testing whether it’s been more than 5000 ms since the time when the program started (millis() returns the number of milliseconds since the program start). What you really want is to compare the current time vs the time when the button was pressed.

pert:
You need to set timepccw to millis() when the button is pressed. The way your code is currently written, this line:

    if (timecurrent - timepccw >= timeccw){

Is testing whether it’s been more than 5000 ms since the time when the program started (millis() returns the number of milliseconds since the program start). What you really want is to compare the current time vs the time when the button was pressed.

thank you, It’s work great.

if (debouncer1.fell()){
  cw = 1;
  timepcw = millis();
}
  if (cw == 1){ 
    timecurrent = millis();
    if (timecurrent - timepcw >= timecw){
      digitalWrite(yellow, HIGH);
    }
  }

If you place this line at the start of your function, it will be synchronized for subsequent TIMERS.

Example:

void loop()
{
timecurrent = millis();

. . .


You might also want to consider this change:

if (cw == 1){
timecurrent = millis();
if (timecurrent - timepcw >= timecw){
digitalWrite(yellow, HIGH);
cw = 0; <———<<<<
}