Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2707184
  • 博文数量: 505
  • 博客积分: 1552
  • 博客等级: 上尉
  • 技术积分: 2514
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-23 18:24
文章分类

全部博文(505)

文章存档

2019年(12)

2018年(15)

2017年(1)

2016年(17)

2015年(14)

2014年(93)

2013年(233)

2012年(108)

2011年(1)

2009年(11)

分类: 嵌入式

2018-08-08 11:20:50

在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也非常简单,上代码:


点击(此处)折叠或打开

  1. #include "ets_sys.h"
  2. #include "osapi.h"
  3. #include "user_interface.h"
  4. //#include "ip_addr.h"
  5. //#include "user_wifi_event.h"
  6.  
  7. os_timer_t sntp_read_timer;
  8. void ICACHE_FLASH_ATTR
  9. sntp_read_timer_callback(void *arg)
  10. {
  11.     uint32_t time = sntp_get_current_timestamp();
  12.     os_printf("time:%d\r\n",time);
  13.     os_printf("date:%s\r\n",sntp_get_real_time(time));
  14. }
  15.  
  16. void ICACHE_FLASH_ATTR
  17. my_sntp_init(void)
  18. {
  19.     sntp_setservername(0,"0.cn.pool.ntp.org");
  20.     sntp_setservername(1,"1.cn.pool.ntp.org");
  21.     sntp_setservername(2,"2.cn.pool.ntp.org");
  22.     sntp_init();
  23.  
  24.     os_timer_disarm(&sntp_read_timer);
  25.     os_timer_setfn(&sntp_read_timer, sntp_read_timer_callback , NULL);
  26.     os_timer_arm(&sntp_read_timer,5000,1);
  27. }



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初始化完成了就正常了。

阅读(3423) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~