C语言中如何求时间段?
我想用Arduino计算开/关灯的周期时间。我用小时+分钟的时间开/关与现在的时间进行比较。问题是,当像此代码一样设置从上午到下午或下午到上午的时间时,时间将不正确。
// 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");
}
如何修复它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您尝试比较开启和关闭时间时,请使用 < code>time.h 库获取当前时间的 Unix 时间戳并使用它进行比较。
请考虑以下比较两次时间的示例:
如果您的应用程序需要本地时间,则可以使用
ctime
将 Unix 时间转换为字符串形式的本地时间。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:
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.