Using RTC and Time for countdown timer to start and stop relays at certain times

Bit of a background of the project,

I am using an RTC to set the time on arduino mega, i am then using now() to set some unsigned long variables at certain times throughout my loop, then calculate back to now()

if (cycleActive == 0) {
    Serial.print("Cycle Is NOT ACTIVE, Next Cycle in: ");
      TFTscreen.stroke(0,0,0);
      TFTscreen.text(nextCyclePrint, 80, 40);
      String nextCycleVal = String(nNow-lastCycleTime-timerCycle);
      nextCycleVal.toCharArray(nextCyclePrint, 6);
   TFTscreen.stroke(0, 255, 0); // set the font color
   TFTscreen.text("Next Cycle:", 5, 40);
      TFTscreen.stroke(255, 0, 0);
   TFTscreen.text(nextCyclePrint, 80, 40);
    Serial.println(nNow-lastCycleTime-timerCycle);
 if (lastCycleTime <= nNow-timerCycle) {                            //If Cycle is Not Active (Flood or Drain) and the time since it finished is time to start
    Serial.println("Cycle Begin");
    if (waterLevel >= wlHigh) {                                                           //Make sure the bucket is not full before starting (Failsafe wont start if there is an issue)
    Serial.println("Start Fill Pump");
    digitalWrite(fillPumpPin,HIGH);
    cycleActive = 1;
    cycleFillActive = 1;
    fillStartTime = nNow;
    cycleStartTime = nNow;
   }
 }

i obviously have other code to do other things and its very messy as iv got no previous coding experience.

Now it works, But it is unreliable and it seems to be a math issue I want it to start 120sec from when the last time it ran, on begin it sets the lastCycleRun variable in the setup so that it has to wait the 120sec to begin the cycle

it runs through the whole cycle fine, but sometimes it starts at 76 seconds sometimes at 13 seconds, i am just wondering if im missing soothing very simple

i changed the unsigned long to long and it was worse it would go 33 seconds over the timer and start then.

i tried making it set the nNow variable at the beginning of the loop to keep it static throughout the loop. but there was no change

i am just wondering if im missing soothing very simple

The rest of your code is missing.

You are uselessly pissing away memory using all those Strings. You don't need to use ANY Strings, and you most certainly do not need to use the String class to convert a long to a string. Stick with strings, and ltoa() and itoa() and dtostrf() and strcat() and strcpy().

The code you have provided is pretty much useless to understand your problem. I will attach a project code i wrote last year for a clock project. It works with a seven segment display and a BCD converter but the main loop is similar yo what you want to do. Sea the “Countdown mode” that is currently commented of in my code and impliment it on your project. I’m using the adafruit RTClib. Licence is mentioned in the project file.

clock_v2.ino (4.03 KB)