|
|
há 5 anos atrás | |
|---|---|---|
| .. | ||
| README.md | há 6 anos atrás | |
| SConscript | há 8 anos atrás | |
| ntp.c | há 6 anos atrás | |
| ntp.h | há 5 anos atrás | |
NTP 是网络时间协议(Network Time Protocol),它是用来同步网络中各个计算机时间的协议。
在 RT-Thread 上实现了 NTP 客户端,连接上网络后,可以获取当前 UTC 时间,并更新至 RTC 中。
首先打开 meunconfig ,配置并开启 netutils 软件包。在配置选项中,默认提供了 3 个 NTP 服务器,保证了 NTP 功能的可靠性。
UTC 时间 又称世界统一时间、世界标准时间、国际协调时间。北京时间为 UTC+8 时间,比 UTC 时间多 8 小时,或者理解为早 8 小时。
API: time_t ntp_get_time(void)
| 参数 | 描述 |
|---|---|
| return | >0: 当前 UTC 时间,=0:获取时间失败 |
示例代码:
#include <ntp.h>
void main(void)
{
time_t cur_time;
cur_time = ntp_get_time();
if (cur_time)
{
rt_kprintf("NTP Server Time: %s", ctime((const time_t*) &cur_time));
}
}
本地时间比 UTC 时间多了时区的概念,例如:北京时间为东八区,比 UTC 时间多 8 个小时。
在 menuconfig 中可以设置当前时区,默认为 8
API: time_t ntp_get_local_time(void)
| 参数 | 描述 |
|---|---|
| return | >0: 当前本地时间,=0:获取时间失败 |
该 API 使用方法与 ntp_get_time() 类似
如果开启 RTC 设备,还可以使用下面的命令及 API 同步 NTP 的本地时间至 RTC 设备。
Finsh/MSH 命令效果如下:
msh />ntp_sync
Get local time from NTP server: Sat Feb 10 15:22:33 2018
The system time is updated. Timezone is 8.
msh />
API: time_t ntp_sync_to_rtc(void)
| 参数 | 描述 |
|---|---|
| return | >0: 当前本地时间,=0:同步时间失败 |