0

I want to make this function in Arduino

uint32_t GetSeconds(int hour_now, int minutes_now, int seconds_now,
                    int hour_future, int minutes_future, int seconds_future);

Something like this, but without using the day involved:

uint32_t future = DateTime(2021, 1, 1, 16, 0, 0).unixtime();
DateTime now = rtc.now();
uint32_t timestamp = now.unixtime();
uint32_t seconds_to_sleep = future - timestamp;
001
  • 13,291
  • 5
  • 35
  • 66
  • Convert all to seconds: `uint32_t now = hour_now * 3600 + minutes_now * 60 + seconds_now`. Do the same for future and subtract. Note this won't work if future time is past midnight. You will need a little extra code for that. – 001 Jul 06 '21 at 13:56
  • Thank you Johnny, but "Note this won't work if future time is past midnight" is the problem, that's where the day(number) come's in.... – mr_applesauce Jul 06 '21 at 14:03
  • If the future time is more than 24 hours out, this function won't work and would require a date parameter. Is it guaranteed to be less that 24 hours? – 001 Jul 06 '21 at 14:13

1 Answers1

0

Convert h,m,s to seconds and subtract. Handle the special case when future is past midnight. In that case, add the differences of each time from midnight.

// Helper function
uint32_t hms_to_seconds(int hour, int minutes, int seconds)
{
    return hour * 3600 + minutes * 60 + seconds;
}

uint32_t GetSeconds(int hour_now, int minutes_now, int seconds_now,
                    int hour_future, int minutes_future, int seconds_future)
{
    uint32_t now = hms_to_seconds(hour_now, minutes_now, seconds_now);
    uint32_t future = hms_to_seconds(hour_future, minutes_future, seconds_future;

    // Future is not past midnight
    if (now < future) {
        return future - now;
    }
    // Future is past midnight
    else {
        uint32_t midnight = hms_to_seconds(24, 0 , 0);
        return (midnight - now) + future;
    }
}

If the future time is more than 24 hours out, this function won't work and would require a date parameter.

001
  • 13,291
  • 5
  • 35
  • 66
  • The future time is no more then 24 hours, so this code will work fine for me, thank you for your time, I greatly appreciate it... – mr_applesauce Jul 06 '21 at 14:37