Trying to make the perfect time On/off code or function

hi, how are you all doing?
in the recent days i've been testing some stuff on an esp32 board. The main target is to turn on and off some outputs triggered by a time. basically at a given time it should turn on the output and, x time later(18 hours), turn it off. In the code below you'll find the important pieces of the code im working on.

// Lights vars.
String lightsTimeOff;
String lightsTimeOn;
time_t  rawLightsTimeInter     =  64800; //interval for light to be on.
time_t  rawLightsTimeOff; // time and date for when the light should turn off, expresed in seconds since 1970
time_t  rawShiftTime; // this variable works as a buffer to store the time error between the time when it should turn on and when it turned on. 
//if it was meant to turn on at 15:30, but you started the device at 16:30, it should store that hour missed expresed in seconds.
// later im planing to use it to correct when it should turn off.

later on the setup() i initialiaze WiFi, NTP and i set the internal RTC to work.
Then i have the loop.

void loop(){
  Date = rtc.getTime("%A, %B %d %Y %H:%M:%S"); 
  Time = rtc.getTime("%X"); //%H:%M:%S 
  Secs = rtc.getTime("%S"); // seconds given from internal RTC
  now  = rtc.getEpoch(); // epoch time given from internal RTC (seconds since 1970....)
  
  if(ledY.state == false && Time == lightsTimeOn ){
    ledY.state = true; digitalWrite(ledY.PIN, HIGH);
    Serial.print("Lights turned on at: "); Serial.println(lightsTimeOn);
    rawLightsTimeOff = now + rawLightsTimeInter; // sum off now time and the on time interval expresed in seconds, resulting in the time and date(expresed in seconds) to turn off the led/lights.
    timeinfo = localtime(&rawLightsTimeOff);
    strftime(buffer, 40, "%A, %B %d %Y %H:%M:%S", timeinfo);
    lightsTimeOff = String(buffer);
    strftime(buffer, 40, "Ligths Time Off is: %c", timeinfo);
    Serial.println(buffer);
  }
  else if ( ledY.state == false && Time => lightsTimeOn ){ // this part is not finished, i was trying to //calculate the time shift when the code starts running after on time.
      rawShiftTime = difftime(now,)//t1 -t2 = rawShiftTime.
  }
  if(ledY.state == true && Date >= lightsTimeOff ){ // turns of led/light at given date.
    ledY.state = false; digitalWrite(ledY.PIN, LOW);
  }

  delay(1000);
}

the problem that i'm having is make a way of triggering this output between a given time, the main issue is triggering also when you started the code already during the ON interval(that why i can't compare only with ">=" inside the if). i'm using intervals beacause you create another problem when using a Time for ON and a Time for OFF, you create redundancies if the OFF Time>ON Time (you turn on at 21hs and turn of at 14hs of the next day).

Really aprecciate any way of help, thank you for your time.
Juancruz279

Please post a complete sketch. You may think you have shared the important pieces, but without the rest of your sketch, it is very impossible to offer assistance other than very vague and general ideas about how to work with time and intervals.

Striving for perfection is admirable, let's get something that works whilst still not quite attaining that worthy goal.

If your sketch is too large, share some of your previous smaller tests of the various functions you are exploiting.

What exact RTC library are you using?

a7

1 Like

lightsTimeOn is a String an so is lightsTimeOff

that's not an issue. If the off time is lower then the on time - then you know that the off time is on next day (+24h)

do you need your on-off times in HH:MM only or HH:MM:SS?

It's all important... post ALL your code.

@juancruz279 working with date and time comparision is much much easier if you use epoch time.

In order to correctly manage an interval between midnight, it is also possible to calculate the equivalent epoch time at the beginning of the day and make a comparison taking it into account

Just a simple example about what I usually do:

hi, thank you for your response.
not really, having "HH:MM" is enough.
now im working on a much advanced way using epoch time. i'll use the native c library "time.h" and just convert all my values to Time_t and so on. i found that the logic to use only strings is not to reliable in some ways. i ran several tests with diferent codes and they work, but in my final code i need other things that relay on storing values over time(temp and humidity), storing time as an integer is more efficient than storing tons of strings.
thank you very much

hi, yes. im using this librarie to manage, Time, NTP and internal RTC(ESP32)

  • Time.h
    -ESP32Time.h (it is a lib created by a community member, used to set and retrieve time from ESP32 internal RTC)
  • esp_sntp.h (from IDF)

i'm currently working with epoch time. in this point i only made a diagram in a sheet of paper on how it would work. im basically having a time for switching on, and a interval of on time. for deducing the off time i'm basically adding to the current epoch time the interval for on time and then ask for that time to then switch off.
the only problem that i'm having is finding the time for switching OFF at the correct time if the time for on was done late.
this could happen in the situation where the esp32 was left off when it is time for switching on, later it would be turn on and the condition of (Date >= time for switching on) will still be true and do the following step, add to this time the interval to deduce the time for switch off, but in this scenario the switch off time would be also delayed, thing that i don't want.
I don't upload this sheet of paper because is not written entirely in english and also is a disaster xd.
i really apreciate all the responses. thank you very much.

Hi, im working with an esp32 and 3 libraries for this time application. time.h, esp_sntp.h, and ESP32Time.h for set and retrieve time from the internal RTC.
the code is extremely large, it has all the wifi and sntp implementations, all the gpio declarations and some functions related to temp and humidity control.
now im struggling to work with arduino IDE and ESP-IDF simultaneously inside vs code, the arduino IDE doesn't run the latest core version for the esp32 and some functions of a few libraries related to FreeRTOS are not working properly. Im trying to implement some system to control timing among a few tasks with queues and semaphores but it doesn't work properly on arduino. i left in pause this part of the project because of this, im trying to implement multitasking and communication beetween tasks properly to then work with this using the time.h library and the classic function, without using strings and only epoch time. as i need to store maybe 120 values for each month, is not memory friendly to do that(im having problems overflowing some stacks and tasks also xd)
im in this kind of mess with my project atm cause i'm working alone and don't have a guide or something to follow, im testing and learning on how to do stuff, mostly relaying on forums like this one.
thank you very much for your time, really aprecciate it
JuanCruz279

Hi, im casting the value with strftime().

This is because you are adding "relative" time respect to the start moment.
In my simple example, this would not happen because start and stop moments are at fixed time, so it's enought using >= instead == in the loop checks.
You should use something similar to avoid this in your skecth.

With ESP32, there is no need for external libraries for the updated time via NTP.
Everything you need is already included in the core.

wifi-NTP-time.ino - Wokwi Arduino and ESP32 Simulator

Your original description is miles away from the RTOS thread / queue / messages / semaphore / multitasking monster you describe in #9 above.

And you are using tools that aren't working.

I think you are waaaaay over-complicating this, and I advise you to step back, describe for yourself and all of us the functioning of the entire system, in plain words.

Most of the time, for something like what I am imagining you up to, there is no need to involve or rely on much of anything but good old code, written at the lowest level with minimal reliance on anything beyond the truly mysterious things, for which you should use (after testing in isolation and getting to know very well) a few well-worn librairies.

As cool as it would be to do otherwise, this seems like a straight-ahead project that would easily be cut like butter with a very simpler approach.

Without even worrying whether you in over your head or not. :wink:

a7

1 Like

hi, thank you for what you are saying. im going to describe my project as good as i can for you.
It's basically an indoor control unit that would be controlled with a mobile app using rainmaker platform, i'm co-working with someone else,im in charge of the electric and electronic design being secure and reliable, also cheap and user friendly.
An indoor is basically a place where you can grow plants inside your house controlling things like lights, temperature & humidity, watering and a few ventilations or fans inside of it. It would have a telemetry function to store profiles for different growing programs and show at the end of the plant cycle how it developed and improve the results next time. I'm in Argentina and recently cannabis growing became legal for medical purposes, only for authorized people with medical needs. the product is aiming to cover the need of people that don't have the time to check for the crop and automate the devices that are usually used in indoors. (lights, vents, fans, watering, alarms for the user, telling the user if x situation ocurred like a sensor failure, temp & humidity measures for displaying and control them, ploting variables over time etc).
As im currently studying in a electronic institute, this is also my final project. As im also making the electronic design, it must comply with regulations, be reliable and secure and be as cheap as posible. it's intended to be a sellable product.
My intention of using freertos is for making tasks run regardless of the states of the others and make a device capable of not failing, using memory properly and making it not restart due to a failure with stack overflow or making the core 1 panic xd (working on it). I'm using this libraries/functionalities from de esp32/IDF and arduino for things that i don't have the knowledge to implement by myself like WiFi and blutethoot.

  • SNTP: Making it capable of automatically set time after resets and during large times being on(avoid drifting and always be synched).
  • Temp & Hum sensor: Working on a reliable way of taking inputs from the sensor and control the heating, hazard prevention(fire) if the sensor is missing, detect and tell the user via app. Also if it's plugged again, continue measuring. Using AHT10 with adafruit library.
  • (RTC) Timed on/cycles: in function of time we need to develop different menus for the user to be able of easily set the times for lights, fans and other devices to control them as easy as posible.
  • RainMaker: Reliable way of making apps with a alredy built and sustained platform developed by espressif. Allows me to controll esp32 from any mobile phone. Also provides cloud services. On the other point, it's alredy a secure platform with already an app on app store and playstore. making us avoid developing apps for two different mobile platforms, avoid security implementation and saving us time and headaches.
  • Cloud services: store and plot variables over time, all must be stored and be later shown to the user. Also the device is constantly showing the state of the indoor inside the app. the app is intended to work with the device connected to internet and remotely be controlled and updated. like a fancy air conditioning that you can controll from your phone with an app.

I'm probably missing some implementations, it's a quick overview of my project, it's for you to get why im planning to use the stuff i mentioned before.

Most of the questions that we are trying to answer to ourselves with the secure capabilites of the device are these one(that we couldn't solve yet). What happens if the sensor goes bad? does it takes false measures and start over heating your plants? does it automatically reconnect to wifi if the router is unpluged? Is it secure to leave it working completely autonomous? are the menus easy to understand? is the first setup easy to understand? does it have enough functions to be worth it? (menus are the predefines way for the user to control and set timing for each thing, lights usually work inside an interval of time, on/off. vent works every half and hour for 15 minutes to recycle aire inside the crop, watering happens every 1 day for 2 mins depending on the water flow/time you have. and so on with the different things u use for the indoor).
You can see that we really aim to reliability and be cost effective with our device, there is a huge aspect of the product to be aimed to people that don't know anything related to troubleshooting or deduce how a device works, we can say that it is "idiot proof".
On the other hand, the code is inteded to have a good debugging and troubleshooting feature logging to terminal with the esp_log lib. Little implementation that make fixing or deduce issues easier.
if u read it all, thank you for your time and feedback. wating for your response, have a good weekend!
JuanCruz279.

hi, im not using any external libraries for NTP, it's the native IDF libary. i'm using the external library for the internal RTC only.
For the "relative times" you describe i understood exacltly what you meant, so im going to set those times before the on time happens, just have in a 30 day period for example, all the time_t values deduced in the moment that the user sets the interval for and the on time. basically i would follow these steps in the code.
first got the amount of days, then the on time and the interval(introduced by the user). for those days calculate the on time expresed in Time_t and the off time. these wouldn't be relative, they would be precise because they store a date and time inside this value. Every day would have it's independant timing for switching and use the comparations that you showed me there.
thank you for your response, have a good weekend.
Juancruz279

Hello, here is an example to do that : t940083.ino - Wokwi ESP32, STM32, Arduino Simulator

It was originally made to answer this topic : Ds3231 on time off time into next day

And a similar topic, basically the same thing : DS3231 RTC on hour/off hour question

1 Like

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