Wiznet makers

chen

Published May 16, 2026 ©

105 UCC

1 WCC

27 VAR

0 Contests

0 Followers

0 Following

Original Link

How to Synchronize Network Time with WIZnet W5500 on STM32F10x?

This STM32F10x project synchronizes network time using SNTP with the WIZnet W5500 Ethernet controller.

COMPONENTS
PROJECT DESCRIPTION

How to Synchronize Network Time with WIZnet W5500 on STM32F10x?

Summary

This STM32F10x project synchronizes network time using SNTP with the WIZnet W5500 Ethernet controller. The STM32 configures W5500 over SPI, applies static network settings, resolves cn.pool.ntp.org through DNS, initializes the SNTP client, and prints the acquired Beijing time through UART. W5500 provides the wired Ethernet interface, hardware TCP/IP stack, UDP socket path, and packet buffering needed for time synchronization in commercial embedded devices.

What the Project Does

The project demonstrates an SNTP-based time synchronization workflow on STM32F10x with W5500. It explains the difference between NTP and SNTP, lists common NTP server domains, then implements an embedded SNTP client using WIZnet ioLibrary. The example uses cn.pool.ntp.org as the NTP server domain and stores the resolved server address in sntp_server_ip[4].

The firmware flow starts with STM32 board initialization: delay, interrupt priority, UART, LED, TIM2, SPI1, W5500 reset pin, and W5500 interrupt pin. It then calls wizchip_initialize() to register SPI access functions, reset W5500, check the chip version, and read PHY status. After that, it writes static network parameters, opens socket 0 in UDP mode, resolves the NTP server domain through DNS, initializes SNTP, and periodically calls SNTP_Work().

The example uses MAC 00:08:DC:11:11:11, local IP 192.168.1.199, subnet 255.255.255.0, gateway 192.168.1.1, DNS server 8.8.8.8, static IP mode, local port 4000, and a China timezone value of 39. When time is acquired, the code sets TimeFlag and prints Beijing time now with year, month, day, hour, minute, and second fields.

Where WIZnet Fits

The exact WIZnet product is W5500. In this architecture, W5500 is the wired Ethernet controller and hardware TCP/IP socket engine between the STM32F10x firmware and the NTP server. The STM32 handles the application sequence, DNS request, SNTP state, UART logging, and LED indication, while W5500 handles Ethernet MAC/PHY operation, UDP socket transport, packet buffering, and SPI-accessible network control.

W5500 is a hardwired TCP/IP stack internet controller with SPI access up to 80 MHz, embedded 10/100 Ethernet MAC and PHY, TCP/UDP/IPv4/ARP/ICMP/IGMP/PPPoE support, 8 independent sockets, and 32 KB of internal Tx/Rx buffer memory. WIZnet also documents ioLibrary as an MCU-independent driver library that supports services including DHCP, DNS, MQTT, SNTP, TFTP, and HTTP Server.

For commercial products, time synchronization is a system function rather than a demo feature. Device logs, scheduled actions, server transactions, audit trails, certificate validity checks, and maintenance records all depend on a sane clock. W5500 keeps the network stack boundary clear: the STM32 only needs stable SPI access, link-state handling, DNS/SNTP calls, timeout handling, and a policy for retrying or reporting time-sync failure.

Implementation Notes

File: W5500_Variable.c
What it configures: static network parameters, DNS server, SNTP server domain, SNTP output buffers, timezone, and time-acquired flag.
Why it matters: SNTP depends on a valid IP configuration and a reachable time server. The project uses DNS first, then passes the resolved NTP server IP into the SNTP client.

 
wiz_NetInfo net_info = {
    {0x00, 0x08, 0xdc,0x11, 0x11, 0x11},
    {192, 168, 1, 199},
    {255,255,255,0},
    {192, 168, 1, 1},
    {8,8,8,8},
    NETINFO_STATIC};

uint8_t sntp_server_name[] = "cn.pool.ntp.org";
uint8_t sntp_server_ip[4] = {0};
uint8_t timezone = 39;
 

This code exists because the W5500 must know the local network identity before the STM32 can send DNS or SNTP traffic. Static IP mode is used in the article, so the gateway, subnet, and DNS server must match the deployed LAN.

File: main.c
What it configures: W5500 initialization, UDP socket setup, DNS resolution, SNTP initialization, and periodic time acquisition.
Why it matters: SNTP uses UDP, so the firmware must open a W5500 UDP socket before running the time-sync workflow.

 
socket(UDP_SOCKET0, Sn_MR_UDP, LocalPort, 0x00);

if (do_dns(ethernet_buf, sntp_server_name, sntp_server_ip))
{
    printf("DNS request failed.\r\n");
    while (1) { }
}

SNTP_init(TCP_SOCKET0, sntp_server_ip, timezone, ethernet_buf);
 

The project then calls SNTP_run(&date) in SNTP_Work(). When the call succeeds, it sets TimeFlag and prints the synchronized Beijing time. This is the point where W5500’s UDP transport becomes visible as an application-level time value for the STM32 firmware.

Practical Tips / Pitfalls

  • Verify SPI and W5500 version-register access before debugging SNTP. The referenced repository recommends checking SPI read/write and chip-version access first. 
  • Check PHY status before DNS or SNTP. The example’s initialization comments explicitly read W5500 PHY configuration bits for link, speed, and duplex status. 
  • Keep local IP, subnet, gateway, and DNS consistent with the real customer LAN. Static IP mode is simple for a demo but fragile in commercial installations.
  • Treat DNS as part of the SNTP dependency chain. If cn.pool.ntp.org cannot resolve, SNTP never reaches the time server.
  • Reserve socket and buffer resources deliberately. W5500 has 8 sockets and 32 KB internal buffer memory, but DNS, SNTP, and other application protocols still need explicit allocation. 
  • Add retry and fallback policy for production firmware. A deployed device should handle DNS failure, NTP server failure, router reboot, cable removal, and long-term clock drift.
  • Decide how trusted time is stored. Commercial products often need a “time valid” flag, last sync timestamp, and log entries for failed synchronization attempts.

FAQ

Q: Why use WIZnet W5500 for SNTP on STM32F10x?
A: W5500 provides the Ethernet MAC/PHY, hardwired TCP/IP engine, UDP socket path, and internal packet buffers required for DNS and SNTP traffic. This lets the STM32F10x firmware focus on time-sync state, application scheduling, and product behavior instead of maintaining a full software TCP/IP stack.

Q: How does W5500 connect to the STM32F10x platform?
A: The example uses the STM32 SPI path through the WIZnet platform layer. The firmware initializes SPI1, W5500 reset and interrupt pins, then calls wizchip_initialize() to register chip-select, single-byte SPI, and burst SPI functions before using socket and protocol APIs.

Q: What role does W5500 play in this SNTP project?
A: W5500 provides the wired network transport for both DNS and SNTP. The STM32 resolves cn.pool.ntp.org, passes the resolved server IP into SNTP_init(), then receives time data through W5500’s UDP socket path and converts it into the datetime structure printed over UART.

Q: Can beginners follow this project?
A: It is suitable for developers who already understand STM32 peripheral initialization, SPI, UART logs, IPv4 addressing, DNS, UDP, and basic time synchronization. For commercial use, the main additions are watchdog recovery, retry logic, failure reporting, and a rule for when the system clock is considered valid.

Q: How does W5500 compare with an LwIP-based SNTP design?
A: With W5500, the TCP/IP stack, socket state, Ethernet MAC/PHY path, and packet buffers are handled by the Ethernet controller, so the STM32 mainly drives SPI and the application state machine. With LwIP, the STM32 firmware typically owns more RAM buffers, timers, packet handling, and driver integration; that can be flexible, but it increases network-stack integration work on small STM32F10x commercial designs.

Source

Original article: CSDN, “测试W5500的第9步_使用SNTP实现网络时间同步,” published on 2025-05-28 and marked as CC 4.0 BY-SA.

Source repository referenced by the article: WIZnet HK, STM32F10x_W5500_Examples, licensed under Mulan PSL v2. The repository describes 10.SNTP as the example for obtaining network time and provides STM32F10x W5500 protocol examples.

WIZnet product reference: W5500 documentation and ioLibrary Driver documentation.

Tags

#W5500 #WIZnet #STM32F10x #STM32F103 #SNTP #NTP #DNS #UDP #Ethernet #SPI #ioLibrary #EmbeddedC #Commercial #NetworkStack

 

 

STM32F10x에서 WIZnet W5500으로 네트워크 시간을 동기화하는 방법은?

요약

이 STM32F10x 프로젝트는 WIZnet W5500 이더넷 컨트롤러를 사용해 SNTP 기반 네트워크 시간 동기화를 구현합니다. STM32는 SPI로 W5500을 설정하고, 고정 네트워크 정보를 적용한 뒤, DNS로 cn.pool.ntp.org를 해석합니다. 이후 SNTP 클라이언트를 초기화하고, 획득한 베이징 시간을 UART로 출력합니다. W5500은 상용 임베디드 장치에서 시간 동기화에 필요한 유선 이더넷 인터페이스, 하드웨어 TCP/IP 스택, UDP 소켓 경로, 패킷 버퍼링을 담당합니다.

프로젝트가 하는 일

이 프로젝트는 STM32F10x와 W5500을 사용해 SNTP 기반 시간 동기화 흐름을 구현합니다. 원문은 NTP와 SNTP의 차이를 설명하고, 자주 사용되는 NTP 서버 도메인을 나열한 뒤, WIZnet ioLibrary를 사용해 임베디드 SNTP 클라이언트를 구성합니다. 예제는 NTP 서버 도메인으로 cn.pool.ntp.org를 사용하며, 해석된 서버 주소를 sntp_server_ip[4]에 저장합니다.

펌웨어 흐름은 STM32 보드 초기화에서 시작합니다. 지연 함수, 인터럽트 우선순위, UART, LED, TIM2, SPI1, W5500 리셋 핀, W5500 인터럽트 핀을 초기화합니다. 이후 wizchip_initialize()를 호출해 SPI 접근 함수를 등록하고, W5500을 리셋하며, 칩 버전을 확인하고, PHY 상태를 읽습니다. 그 다음 고정 네트워크 파라미터를 기록하고, 소켓 0을 UDP 모드로 열고, DNS로 NTP 서버 도메인을 해석한 뒤, SNTP를 초기화하고 SNTP_Work()를 주기적으로 호출합니다.

예제는 MAC 00:08:DC:11:11:11, 로컬 IP 192.168.1.199, 서브넷 255.255.255.0, 게이트웨이 192.168.1.1, DNS 서버 8.8.8.8, 고정 IP 모드, 로컬 포트 4000, 중국 시간대 값 39를 사용합니다. 시간이 정상적으로 획득되면 코드는 TimeFlag를 설정하고, 연·월·일·시·분·초 필드로 구성된 Beijing time now 값을 UART로 출력합니다.

WIZnet이 들어가는 위치

이 프로젝트에서 사용되는 WIZnet 제품은 W5500입니다. 이 구조에서 W5500은 STM32F10x 펌웨어와 NTP 서버 사이에 위치하는 유선 이더넷 컨트롤러이자 하드웨어 TCP/IP 소켓 엔진입니다. STM32는 애플리케이션 순서, DNS 요청, SNTP 상태, UART 로그, LED 표시를 처리하고, W5500은 Ethernet MAC/PHY 동작, UDP 소켓 전송, 패킷 버퍼링, SPI 기반 네트워크 제어를 담당합니다.

W5500은 하드웨어 TCP/IP 스택 기반 인터넷 컨트롤러이며, 최대 80 MHz SPI 접근, 내장 10/100 Ethernet MAC 및 PHY, TCP/UDP/IPv4/ARP/ICMP/IGMP/PPPoE 지원, 8개 독립 소켓, 32 KB 내부 Tx/Rx 버퍼를 제공합니다. WIZnet ioLibrary는 MCU 독립형 드라이버 라이브러리이며 DHCP, DNS, MQTT, SNTP, TFTP, HTTP Server 같은 서비스를 지원합니다.

상용 제품에서 시간 동기화는 단순한 데모 기능이 아니라 시스템 기능입니다. 장치 로그, 예약 동작, 서버 트랜잭션, 감사 기록, 인증서 유효성 확인, 유지보수 기록은 모두 정상적인 시스템 시간에 의존합니다. W5500을 사용하면 네트워크 스택의 경계가 명확해집니다. STM32는 안정적인 SPI 접근, 링크 상태 처리, DNS/SNTP 호출, 타임아웃 처리, 시간 동기화 실패 시 재시도 또는 오류 보고 정책에 집중하면 됩니다.

구현 참고 사항

파일: W5500_Variable.c
설정 내용: 고정 네트워크 파라미터, DNS 서버, SNTP 서버 도메인, SNTP 출력 버퍼, 시간대, 시간 획득 플래그
중요한 이유: SNTP는 유효한 IP 설정과 접근 가능한 시간 서버에 의존합니다. 이 프로젝트는 먼저 DNS를 수행한 뒤, 해석된 NTP 서버 IP를 SNTP 클라이언트에 전달합니다.

 
wiz_NetInfo net_info = {
    {0x00, 0x08, 0xdc,0x11, 0x11, 0x11},
    {192, 168, 1, 199},
    {255,255,255,0},
    {192, 168, 1, 1},
    {8,8,8,8},
    NETINFO_STATIC};

uint8_t sntp_server_name[] = "cn.pool.ntp.org";
uint8_t sntp_server_ip[4] = {0};
uint8_t timezone = 39;
 

이 코드는 STM32가 DNS 또는 SNTP 트래픽을 보내기 전에 W5500이 로컬 네트워크 식별 정보를 알고 있어야 하기 때문에 필요합니다. 원문 예제는 고정 IP 모드를 사용하므로, 게이트웨이, 서브넷, DNS 서버가 실제 배포 LAN 환경과 일치해야 합니다.

파일: main.c
설정 내용: W5500 초기화, UDP 소켓 설정, DNS 해석, SNTP 초기화, 주기적 시간 획득
중요한 이유: SNTP는 UDP를 사용하므로, 시간 동기화 흐름을 실행하기 전에 펌웨어가 W5500 UDP 소켓을 열어야 합니다.

 
socket(UDP_SOCKET0, Sn_MR_UDP, LocalPort, 0x00);

if (do_dns(ethernet_buf, sntp_server_name, sntp_server_ip))
{
    printf("DNS request failed.\r\n");
    while (1) { }
}

SNTP_init(TCP_SOCKET0, sntp_server_ip, timezone, ethernet_buf);
 

이후 프로젝트는 SNTP_Work()에서 SNTP_run(&date)를 호출합니다. 호출이 성공하면 TimeFlag를 설정하고 동기화된 베이징 시간을 출력합니다. 이 지점에서 W5500의 UDP 전송 기능은 STM32 펌웨어가 사용할 수 있는 애플리케이션 수준의 시간 값으로 변환됩니다.

실무 팁 / 주의점

  • SNTP를 디버깅하기 전에 SPI와 W5500 버전 레지스터 접근을 확인해야 합니다. SPI 읽기/쓰기와 칩 버전 확인이 먼저 안정적으로 동작해야 합니다.
  • DNS 또는 SNTP를 실행하기 전에 PHY 상태를 확인해야 합니다. 예제 초기화 흐름은 W5500 PHY 설정 비트를 읽어 링크, 속도, 듀플렉스 상태를 확인합니다.
  • 로컬 IP, 서브넷, 게이트웨이, DNS는 실제 고객 LAN과 일치해야 합니다. 고정 IP 모드는 데모에는 단순하지만 상용 설치에서는 취약할 수 있습니다.
  • DNS는 SNTP의 의존 요소로 다뤄야 합니다. cn.pool.ntp.org를 해석하지 못하면 SNTP는 시간 서버에 도달할 수 없습니다.
  • 소켓과 버퍼 자원을 의도적으로 예약해야 합니다. W5500은 8개 소켓과 32 KB 내부 버퍼를 제공하지만, DNS, SNTP, 기타 애플리케이션 프로토콜은 명시적인 자원 할당이 필요합니다.
  • 양산 펌웨어에는 재시도 및 폴백 정책이 필요합니다. 배포된 장치는 DNS 실패, NTP 서버 장애, 라우터 재시작, 케이블 분리, 장기적인 클록 드리프트를 처리해야 합니다.
  • 신뢰 가능한 시간 상태를 어떻게 저장할지 정해야 합니다. 상용 제품은 보통 “시간 유효” 플래그, 마지막 동기화 시각, 동기화 실패 로그를 별도로 관리해야 합니다.

FAQ

Q: STM32F10x에서 SNTP를 구현할 때 왜 WIZnet W5500을 사용하나요?
A: W5500은 DNS 및 SNTP 트래픽에 필요한 Ethernet MAC/PHY, 하드웨어 TCP/IP 엔진, UDP 소켓 경로, 내부 패킷 버퍼를 제공합니다. STM32F10x 펌웨어는 전체 소프트웨어 TCP/IP 스택을 유지하는 대신 시간 동기화 상태, 애플리케이션 스케줄링, 제품 동작에 집중할 수 있습니다.

Q: W5500은 STM32F10x 플랫폼에 어떻게 연결되나요?
A: 예제는 STM32의 SPI 경로를 WIZnet 플랫폼 계층으로 연결합니다. 펌웨어는 SPI1, W5500 리셋 핀, W5500 인터럽트 핀을 초기화한 뒤 wizchip_initialize()를 호출합니다. 이 과정에서 칩 셀렉트, 단일 바이트 SPI, 버스트 SPI 함수가 등록되고 이후 소켓 및 프로토콜 API를 사용할 수 있습니다.

Q: 이 SNTP 프로젝트에서 W5500은 어떤 역할을 하나요?
A: W5500은 DNS와 SNTP를 위한 유선 네트워크 전송 경로를 제공합니다. STM32는 cn.pool.ntp.org를 해석하고, 해석된 서버 IP를 SNTP_init()에 전달합니다. 이후 W5500의 UDP 소켓 경로를 통해 시간 데이터를 수신하고, 이를 UART로 출력되는 datetime 구조체 값으로 변환합니다.

Q: 초보자도 따라할 수 있나요?
A: STM32 주변장치 초기화, SPI, UART 로그, IPv4 주소 체계, DNS, UDP, 기본 시간 동기화 개념을 이해하는 개발자에게 적합합니다. 상용 제품으로 확장하려면 watchdog 복구, 재시도 로직, 실패 보고, 시스템 시간이 언제 유효한지 판단하는 규칙이 추가로 필요합니다.

Q: W5500 방식은 STM32에서 LwIP 기반 SNTP를 구현하는 방식과 어떻게 다른가요?
A: W5500을 사용하면 TCP/IP 스택, 소켓 상태, Ethernet MAC/PHY 경로, 패킷 버퍼가 이더넷 컨트롤러 내부에서 처리되므로 STM32는 주로 SPI와 애플리케이션 상태 머신을 구동합니다. LwIP를 사용하면 STM32 펌웨어가 RAM 버퍼, 타이머, 패킷 처리, 드라이버 통합을 더 많이 담당하므로 유연성은 있지만 작은 STM32F10x 상용 설계에서는 네트워크 스택 통합 작업이 증가합니다.

출처

Original article: CSDN, “测试W5500的第9步_使用SNTP实现网络时间同步,” 2025-05-28 게시, CC 4.0 BY-SA로 표시됨.
https://blog.csdn.net/weixin_42550185/article/details/148284560?spm=1001.2014.3001.5502

Source repository referenced by the article: WIZnet HK, STM32F10x_W5500_Examples, Mulan PSL v2 라이선스. 저장소는 10.SNTP를 네트워크 시간 획득 예제로 설명하며 STM32F10x W5500 프로토콜 예제 세트를 제공합니다.
https://gitee.com/wiznet-hk/STM32F10x_W5500_Examples

WIZnet product reference: W5500 documentation and ioLibrary Driver documentation.
https://docs.wiznet.io/Product/Chip/Ethernet/W5500

태그

#W5500 #WIZnet #STM32F10x #STM32F103 #SNTP #NTP #DNS #UDP #Ethernet #SPI #ioLibrary #EmbeddedC #Commercial #NetworkStack

Documents
Comments Write