Using one timer to start other timer

Hi, I was hoping someone could help me.

I am trying to start a timer at the start of the code. Once this timer is finished it will start a second timer and be able to repeat this process over and over again.

The first timer is a delay till an output is turned on and the second timer is for how long the output will say on.

The code I have so far is below. Any help would be much appreciated!

#include <millisDelay.h>

int LED = 2;
const unsigned long DELAY_TIME = 10000;
const unsigned long DELAY_TIME1 = 2000;

millisDelay moisture_timer;
millisDelay moisture_on;



void setup() {
  Serial.begin(9600);

  for (int i = 5; i > 0; i--) { // just to give a little time before it all starts
    delay(1000);
    Serial.print(i); Serial.print(' ');

  }
  Serial.println();

  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);



}

void loop() {

  moisture_timer.start(DELAY_TIME);

  if (moisture_timer.justFinished()) {
    moisture_on.start(DELAY_TIME1);
    digitalWrite(2, HIGH);

    if (moisture_on.justFinished()) {
      digitalWrite(2, LOW);

    }
  }
}

Like this you mean?

(got rid of the library! :wink: )

int LED = 2;
const unsigned long DELAY_TIME = 10000;
const unsigned long DELAY_TIME1 = 2000;

unsigned long moisture_timer, moisture_on;

void setup() {
  Serial.begin(9600);

  for (int i = 5; i > 0; i--) { // just to give a little time before it all starts
    delay(1000);
    Serial.print(i); Serial.print(' ');

  }
  Serial.println();

  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);

  moisture_timer =  moisture_on = millis();

}

void loop() {

  if (millis()-moisture_timer> DELAY_TIME) {
    if(digitalRead(LED)==LOW){
      moisture_on = millis(); 
    }
    digitalWrite(LED, HIGH);

    if (millis()-moisture_on> DELAY_TIME1) {
      digitalWrite(LED, LOW);
      moisture_timer = millis();
    }
  }
}

https://wokwi.com/projects/347143872590119506

hope that helps...

1 Like

That works, thank you very much.

consider

int LED = LED_BUILTIN;

const unsigned long DELAY_TIME = 10000;
const unsigned long DELAY_TIME1 = 2000;

unsigned long msecPeriod;
unsigned long msecLst;
unsigned long msec;

void loop ()
{
    msec = millis ();

    if ((msec - msecLst) >= msecPeriod)  {
        msecLst = msec;

        if (HIGH == digitalRead (LED))  {
            msecPeriod = DELAY_TIME;
            digitalWrite (LED, LOW);
        }
        else  {
            msecPeriod = DELAY_TIME1;
            digitalWrite (LED, HIGH);
        }
    }
}

void setup ()
{
    Serial.begin (9600);
    pinMode      (LED, OUTPUT);
    digitalWrite (LED, LOW);
}
1 Like

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