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?