1.定义宏SNTP_SET_SYSTEM_TIME为自定义的回调函数
#define SNTP_SET_SYSTEM_TIME sntp_set_system_time
#if !defined SNTP_SET_SYSTEM_TIME || defined __DOXYGEN__
#define SNTP_SET_SYSTEM_TIME(sec) LWIP_UNUSED_ARG(sec)
#endif
void sntp_set_system_time(uint32_t sec)
{
struct tm current_time_val;
time_t current_time = (time_t)sec;
uint8_t hour, min, secx, ampm;
uint8_t year, month, date, week;
uint8_t tbuf[40];
uint8_t t = 0;
#ifdef _MSC_VER
localtime_s(¤t_time_val, ¤t_time);
#else
localtime_r(¤t_time, ¤t_time_val);
#endif
printf("北京时间:%02d-%02d-%d %02d:%02d:%02d\r\n",
current_time_val.tm_year + 1900 - 2000,
current_time_val.tm_mon + 1,
current_time_val.tm_mday,
current_time_val.tm_hour + 8,
current_time_val.tm_min,
current_time_val.tm_sec);
}
2.设置SNTP轮询模式,设置服务器,启动SNTP。
#include "sntp.h"
#include "time.h"
#include <netdb.h>
#define HOST_NAME "ntp1.aliyun.com" /*阿里云NTP服务器域名 */
struct hostent *server;
ip_addr_t sntp_server;
server = gethostbyname((char *)HOST_NAME); /* 对aliyun服务器地址解析 */
memcpy(&sntp_server,server->h_addr,server->h_length); /* 把解析好的地址存放在mqtt_ip变量当中 */
sntp_setoperatingmode(SNTP_OPMODE_POLL);
//打印经过域名解析的IP地址
printf("dns ip: %d.%d.%d.%d",sntp_server.addr&0x000000ff,(sntp_server.addr&0x0000ff00)>>8,
(sntp_server.addr&0x00ff0000)>>16,(sntp_server.addr&0xff000000)>>24);
sntp_init();
/* 加入授时中心的IP信息 */
sntp_setserver(0, &sntp_server);
注意点:内存池一定要设置大点,否则可能报错sys_timeout: timeout != NULL, pool MEMP_SYS_TIMEOUT is empty
设置方法:
//如果报错,则将这个宏参数调大一点
#define MEMP_NUM_SYS_TIMEOUT 6