Sleep until 7:59 am

Good afternoon,

I’ll be diving further into this tomorrow, but thought to ask folks who may have already come up with a concise way to do it: I’d like to put a device to sleep until 7:59am everyday. I assume I’ll be using the built in Time library functions in combination with one of the various sleep modes.

Traditionally I always just used a duration of milliseconds to time things, but I’m integrating with a secondary device that is working off a standard 12 hour clock, so it would be nice to just pull the time of day from the Particle Cloud, and simply sleep / wake based on that.

Is the simplest way to pull the time of day, calculate number of milliseconds until 7:59, and then sleep for that duration? If so, an example of utilizing the Time library to do something like this would save some time…though I do enjoy the journey of trial and error.

-RC

The best way to do this IMHO and if you need to wake precisely at 07:59:00 would be to use an external RTC (because the Argon does not have an RTC). I have a sensor setup that uses a DS3231 RTC and can be set to sleep ‘out of hours’ and wake without worrying about maintaining accurate time itself.

If I were using the Cloud instead of the RTC then first ensure the time has been synced and I would use local() to get time in seconds and then %86400 to get the seconds since 00:00:00 - then you need some logic that handles how many seconds you sleep for i.e. from time you go to sleep until 07:59 (which could be the next day) and also handling DST. You could define a macro to calculate this = h * 3600 + m * 60 + s or a function.

1 Like

@armor, I appreciate your thoughts on this. I should be good just using the Cloud as it doesn’t have to be exact, easily give-or-take a couple minutes. The eternally useful modulus comes in handy again, good idea. Gonna jump into it and make it happen now, thanks again.

Here’s what I came up with based on your suggestions…more steps and variables than necessary, but it helps break the process down and is therefore more readable for future me (I also call Particle.syncTime() right before this function):

unsigned int sleepTill(unsigned int hour, unsigned int minute, unsigned int second)
    {
        unsigned int currentTime = Time.local();
        unsigned int midnight = (currentTime - (currentTime % 86400));
        unsigned int wakeTime = (midnight + (hour * 3600) + (minute * 60) + (second));
        unsigned int secondsTillWake = (wakeTime - currentTime);
        return secondsTillWake;
    }