1、首先配置LWIP支持SNTP
然后在opt.h中增加一个timeout->LWIP_SNTP
防止出现类似
Assertion "sys_timeout: timeout != NULL, pool MEMP_SYS_TIMEOUT is empty" failed at line 190 in ../Middlewares/Third_Party/LwIP/src/core/timeouts.c
这样的错误。
1
2
3
4
5/** * The number of sys timeouts used by the core stack (not apps) * The default number of timeouts is calculated here for all enabled modules. */ #define LWIP_NUM_SYS_TIMEOUT_INTERNAL (LWIP_TCP + LWIP_SNTP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + PPP_NUM_TIMEOUTS + (LWIP_IPV6 * (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD)))
在使用sntp之前,需要对其进行初始化,初始化放在lwip初始化之后就行了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18void set_sntp_server_list(void) { uint32_t server_list[SNTP_MAX_SERVERS] = {0x9f64a8c0}, // 我本地windows创建的NTP服务器,192.168.100.159 ip_addr_t sntp_server; // 本身支持多个服务器,我们这里SNTP_MAX_SERVERS = 1 for(int i = 0; i < SNTP_MAX_SERVERS; i++) { sntp_server.addr = server_list[i]; sntp_setserver(i, &sntp_server); } } void dev_sntp_init(void) { sntp_setoperatingmode(SNTP_OPMODE_POLL); sntp_init(); set_sntp_server_list(); }
2、在使用LWIP进行嵌入式程序开发时,实现秒级的时间校准,只需要重新定义SNTP_SET_SYSTEM_TIME(sec)这个函数就可以了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15#define SNTP_SET_SYSTEM_TIME sntp_set_time void sntp_set_time(time_t sntp_time) { if(sntp_time == 0) { return; } struct tm *time; sntp_time += (8*3600); // 时区 time = localtime(&sntp_time); printf("%d:%d:%drn", time->tm_hour,time->tm_min,time->tm_sec); printf("%d:%d:%drn", time->tm_year+1900,time->tm_mon+1,time->tm_mday); }
3、参考sntp_otp.h中的介绍:
/** SNTP macro to change system time in seconds
* Define SNTP_SET_SYSTEM_TIME_US(sec, us) to set the time in microseconds
* instead of this one if you need the additional precision. Alternatively,
* define SNTP_SET_SYSTEM_TIME_NTP(sec, frac) in order to work with native
* NTP timestamps instead.
*/
只需要重新实现SNTP_SET_SYSTEM_TIME_US(sec, us)这个函数就可以了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15#define SNTP_SET_SYSTEM_TIME_US sntp_set_timeus void sntp_set_timeus(time_t sntp_time, int us) { if(sntp_time == 0) { return; } struct tm *time; sntp_time += (8 * 3600); // 时区 time = localtime(&sntp_time); printf("%d:%d:%d.%drn", time->tm_hour,time->tm_min,time->tm_sec, us); printf("%d:%d:%drn", time->tm_year+1900,time->tm_mon+1,time->tm_mday); }
最后
以上就是美满冰棍最近收集整理的关于STM32 LWIP SNTP实现毫秒级的时间校准的全部内容,更多相关STM32内容请搜索靠谱客的其他文章。
发表评论 取消回复