How to find time period in C?

Viewed 81

I want to calcute peroid time for turn on/off the light with Arduino. I use hour+minute of time on/off compare with time now. The problem is the time will not correct when set time from AM to PM or PM to AM like this code.

// On 23:30
int on_hour = 23;
int on_min = 30;

// Off 08:30
int off_hour = 8;
int off_min = 30;

time_t t = now(); // store the current time in time variable t
hour(t);          // returns the hour for the given time t
minute(t);        // returns the minute for the given time t

int t_now = hour(t)+minute(t); 

int t_on = on_hour + on_min;   //53
int t_off = off_hour + off_min;  //38

//open 23:30 - 08:30
if (t_on > t_off){                  
    if(t_now > t_on)  // if t_now = 01:30 = 31, 31 less than 53 the light will  close
        Serial.printf("open");
    else(if t_now > t_off)    
        Serial.printf("close");
}

//////////////////////////////////////////////////////////////////////////

// On 08:30
on_hour = 8
on_min = 30

// Off 21:30
off_hour = 21
off_min = 30


t_on = on_hour + on_min  // 38
t_off = off_hour + off_min // 51

//open 08:30 - 21:30
if (t_on < t_off){                  
    if(t_now < t_on)  // if t_now = 20:30 = 50, 50 more than 38 the light will  close
        Serial.printf("open");
    else(if t_now > t_off)   
        Serial.printf("close");
}

How to fix it?

1 Answers

As you're trying to compare on and off time, use time.h library to obtain Unix timestamp of the current time and use that for comparison.

Consider the following example for comparing two times:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
  time_t begin = -1, end = -1; 
  // Capture begin unix time
  time(&begin);
  // Wait for two seconds
  sleep(2);
  // Capture end unix time
  time(&end);

  if (begin < 0 || end < 0) {
    printf("Error obtaining Unix timestamp.\n");
    exit(1);
  }

  // Comparison operators can now be used
  if (begin < end) {
    printf("Begin timestamp (%lu) is smaller than end timestamp (%lu).\n", begin, end);
  }

  return 0;
}

If you need local time for your application, you can use ctime to convert the Unix time to a local time in form of a string.

Related