您的位置:首页 > 编程语言 > PHP开发

【ESP8266】使用SNTP接口获取时间

2016-04-28 13:58 561 查看
在ESP8266给出的官方文档中,提到了SNTP接口,主要有以下函数:

sntp_setserver

功能:通过 IP 地址设置 SNTP 服务器,一共最多支持设置 3 个 SNTP 服务器。

函数定义:void sntp_setserver(unsigned char idx, ip_addr_t *addr)

参数:

unsigned char idx :SNTP 服务器编号,最多⽀持3个 SNTP 服务器(0~2);0 号为主服务器,1号和2 号为备用服务器。

ip_addr_t *addr :IP 地址;用户需自行确保,传入的是合法SNTP服务器。

返回:无

sntp_setservername

功能:通过域名设置 SNTP 服务器,一共最多支持设置 3 个 SNTP 服务器。

函数定义:void sntp_setservername(unsigned char idx, char *server)

参数:

unsigned char idx :SNTP 服务器编号,最多⽀持3个SNTP服务器(0 ~ 2);0号为主服务器,1号和2号为备用服务器。

char *server :域名;用户需自行确保,传入的是合法 SNTP 服务器。

返回:无

sntp_init

功能:SNTP 初始化

函数定义:void sntp_init(void)

参数:无

返回:无

sntp_stop

功能:SNTP 关闭

函数定义:void sntp_stop(void)

参数:无

返回:无

sntp_get_current_timestamp

功能:查询当前距离基准时间( 1970.01.01 00: 00: 00 GMT + 8)的时间戳,单位:秒

函数定义:uint32 sntp_get_current_timestamp()

参数:无

返回:距离基准时间的时间戳

sntp_get_real_time

功能:查询实际时间( GMT + 8)

函数定义:char* sntp_get_real_time(long t)

参数:long t - 与基准时间相距的时间戳

返回:实际时间

在ESP8266上使用STNP也非常简单,上代码:

#include "ets_sys.h"
#include "osapi.h"
#include "user_interface.h"
//#include "ip_addr.h"
//#include "user_wifi_event.h"

os_timer_t sntp_read_timer;
void ICACHE_FLASH_ATTR
sntp_read_timer_callback(void *arg)
{
uint32_t time = sntp_get_current_timestamp();
os_printf("time:%d\r\n",time);
os_printf("date:%s\r\n",sntp_get_real_time(time));
}

void ICACHE_FLASH_ATTR
my_sntp_init(void)
{
sntp_setservername(0,"0.cn.pool.ntp.org");
sntp_setservername(1,"1.cn.pool.ntp.org");
sntp_setservername(2,"2.cn.pool.ntp.org");
sntp_init();

os_timer_disarm(&sntp_read_timer);
os_timer_setfn(&sntp_read_timer, sntp_read_timer_callback , NULL);
os_timer_arm(&sntp_read_timer,5000,1);
}

user_sntp_init函数首先设置3个STNP的服务器,然后调用sntp_init函数初始化,最后设置一个定时器,每5秒从SNTP接口获取时间并打印出来,打印效果如下:

……

time:1461851702

date:Thu Apr 28 13:55:02 2016

time:1461851707

date:Thu Apr 28 13:55:07 2016

time:1461851712

date:Thu Apr 28 13:55:12 2016

time:1461851717

date:Thu Apr 28 13:55:17 2016

time:1461851722

date:Thu Apr 28 13:55:22 2016

……

另外要注意一些事项:

1、ESP8266要联网。

2、sntp初始化有一定的时间,所以第一次打印时可能会出现「please start sntp first !」警告,等sntp初始化完成了就正常了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: