# How to calculate remaining time?

Hi there,

I’m not a die-hard programmer, therefore I would like to asked you for some advice.

With my Photon I’ve made a lighting system in my room with a lot of ws2812’s and my phone. Very cool of course ^.^

I would like it turn on at 8 O’clock in the morning. So with `if(Time.hour() == 8) {` that happens.
Only, I don’t want my Photon to be on the whole night. Luckily there for `System.sleep(SLEEP_MODE_DEEP,60);` exists were ‘60’ is the time it has to be in sleep mode seconds.

I want my photon to go to sleep when I press the ‘sleep’ button on my phone and wake up at, lets say, 7’oclock.
But I don’t turn off my light at the same time every day. So the ‘sleep mode seconds’ has to be a variable.

My question: any good advice on how I can calculate the remaining time from the moment I press the ‘sleep’ button till 7 o’clock witch can be filled in instead of the ‘60’?

Happy Making!

• Mark

Hmm, a very low key solution would be to calculate it (untested code).

``````int mins = 60 - Time.minute(); //Minutes left in current hour.
var hour = Time.hour();

if (hour == 23) hour=0;
else hour++;

if (hour > 7)
{
mins += (24-hour) * 60 + (7*60);
} else {
mins += (7-hour) * 60;
}
``````

//sleep for mins * 60
Alternatively you could wake up every x minutes and check the time, but energywise its not great, and if the onboard led is visible it will distract.

Hint:
The clock works in seconds since Jan 1st(?), 1970. Its called Epoch or Unix time.
You can calculate the future ‘Wake Time’ in seconds since 1970.
You can measure the time that the device goes to 'Sleep".
‘Wake Time’ - ‘Sleep Time’ = Sleep timer in seconds.

By using the seconds directly, you avoid rolling over dates.
The real question is how to calculate the number of seconds between now() and futureTime().

something like this:

``````void setup() {
// put your setup code here, to run once:

}

void loop()
{
unsigned long sleepTime;
if(true)
{
int hour = Time.hour();
if (hour <= 23 && hour > 7)
{
time_t rightNow = Time.now();  // UNIX timestamp for rightNow
time_t midnightTonight = tmConvert_t (Time.year(), Time.month(), Time.day(), 23, 59, 59); //Unix timestamp for midnight
sleepTime = (midnightTonight - rightNow) + (7 * 3600); // add 7 hours to midnight
}
else
{
time_t rightNow = Time.now();  // UNIX timestamp for rightNow
time_t sevenAM = tmConvert_t (Time.year(), Time.month(), Time.day(), 7, 0, 0); //Unix timestamp for 7am
sleepTime = (sevenAM - rightNow);
}
//wakey wakey
}

}

time_t tmConvert_t(int YYYY, byte MM, byte DD, byte hh, byte mm, byte ss)
{
struct tm t;
t.tm_year = YYYY-1970;
t.tm_mon = MM;
t.tm_mday = DD;
t.tm_hour = hh;
t.tm_min = mm;
t.tm_sec = ss;
t.tm_isdst = 0;
time_t t_of_day = mktime(&t);
return t_of_day;
}

``````

``````*In file included from ../inc/spark_wiring.h:29:0,*