---
title: "How to Build Reliable TCP/UDP Communication with W5500 on STM32?"
url: "https://maker.wiznet.io/chen/projects/how-to-build-reliable-tcp-udp-communication-with-w5500-on-stm32/"
markdown_url: "https://maker.wiznet.io/chen/projects/how-to-build-reliable-tcp-udp-communication-with-w5500-on-stm32/md"
type: "UCC: User Created Content"
author: "yayaer2"
author_url: "https://blog.csdn.net/dafurong/article/details/148143390?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522dc42599d58b3c56450215f4df1088253%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=dc42599d58b3c56450215f4df1088253&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~time_text~default-9-148143390-null-null.142^v102^pc_search_result_base9&utm_term=W5500&spm=1018.2226.3001.4187"
editor: "WIZnet"
editor_url: "https://maker.wiznet.io/"
original_author: "yayaer2"
original_url: "https://blog.csdn.net/dafurong/article/details/148143390?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522dc42599d58b3c56450215f4df1088253%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=dc42599d58b3c56450215f4df1088253&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~time_text~default-9-148143390-null-null.142^v102^pc_search_result_base9&utm_term=W5500&spm=1018.2226.3001.4187"
published: "2026-04-10"
language: "en"
likes: 0
views: 323
comments: 0
source: "WIZnet Makers (https://maker.wiznet.io/)"
---

# How to Build Reliable TCP/UDP Communication with W5500 on STM32?

> This project demonstrates how to implement reliable TCP/UDP communication using the WIZnet W5500 Ethernet controller with an STM32 MCU.

Original author: yayaer2 (source: https://blog.csdn.net/dafurong/article/details/148143390?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522dc42599d58b3c56450215f4df1088253%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=dc42599d58b3c56450215f4df1088253&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~time_text~default-9-148143390-null-null.142^v102^pc_search_result_base9&utm_term=W5500&spm=1018.2226.3001.4187)

## Article

## How to Build Reliable TCP/UDP Communication with W5500 on STM32?

### Summary

This project demonstrates how to implement reliable TCP/UDP communication using the WIZnet W5500 Ethernet controller with an STM32 MCU. The W5500 provides a hardware TCP/IP stack, eliminating the need for software stacks like LwIP. In this architecture, STM32 handles application logic while W5500 acts as the network transport engine, enabling deterministic and low-overhead Ethernet communication.

### What the Project Does

The system builds a complete **embedded Ethernet communication pipeline** using STM32 and W5500.

Core functions include:

- SPI-based communication between STM32 and W5500

- Network configuration (MAC, IP, subnet, gateway)

- TCP/UDP socket creation and management

- Data transmission and reception

- Connection state monitoring

System flow:
STM32 → SPI → W5500 → Ethernet → Remote Host

Two main communication modes are used:

#### TCP Mode

- Connection-oriented and reliable

- Handles retransmission internally (via W5500)

- Suitable for MQTT, HTTP, remote control

#### UDP Mode

- Connectionless and lower latency

- Suitable for streaming, broadcast, or sensor bursts

This architecture is widely used in:

- Industrial IoT devices

- Embedded gateways

- Remote monitoring systems

### Where WIZnet Fits

The **W5500** acts as a dedicated **hardware TCP/IP offload engine** in the STM32 system.

#### Role of W5500

- Handles full TCP/IP stack in hardware (TOE)

- Manages packet buffering and retransmission

- Supports up to **8 simultaneous sockets**

#### Role of STM32

- Executes application logic

- Controls W5500 via SPI

- Processes received data and generates responses

This separation is important because:

- STM32 does not need to run LwIP or RTOS networking tasks

- CPU and RAM usage are significantly reduced

- Network timing becomes more predictable

Compared to **STM32 + LwIP (software stack)**:

- LwIP requires careful memory allocation and RTOS tuning

- Interrupt and network timing can interfere with each other

- W5500 simplifies firmware and improves stability

### Implementation Notes

The original article explains W5500 communication flow but does not provide a full repository.

Below is a **conceptual integration example based on WIZnet ioLibrary**, adapted for STM32:

// Conceptual integration example based on WIZnet ioLibrary

#include "wizchip_conf.h"
#include "socket.h"

// SPI functions implemented using STM32 HAL
void spi_write(uint8_t data);
uint8_t spi_read(void);

void wizchip_spi_init(void) {
reg_wizchip_spi_cbfunc(spi_read, spi_write);
}

void network_init(void) {
uint8_t txsize[8] = {2,2,2,2,2,2,2,2};
uint8_t rxsize[8] = {2,2,2,2,2,2,2,2};

wizchip_init(txsize, rxsize);

wiz_NetInfo netinfo = {
.mac = {0x00,0x08,0xDC,0xAA,0xBB,0xCC},
.ip = {192,168,1,100},
.sn = {255,255,255,0},
.gw = {192,168,1,1}
};

wizchip_setnetinfo(&netinfo);
}

void tcp_server(void) {
socket(0, Sn_MR_TCP, 5000, 0);
listen(0);

while (1) {
if (getSn_SR(0) == SOCK_ESTABLISHED) {
uint8_t buf[128];
int len = recv(0, buf, sizeof(buf));

if (len > 0) {
send(0, buf, len); // echo back
}
}
}
}

**Why this matters:**

- Shows how STM32 integrates W5500 via SPI

- Demonstrates **hardware socket-based networking**

- Highlights reduced firmware complexity compared to LwIP

For MQTT:

- STM32 runs MQTT client logic

- W5500 provides TCP transport

- Enables cloud connectivity without full TCP/IP stack overhead

### Practical Tips / Pitfalls

- Verify **SPI configuration (mode, speed, CS timing)** on STM32

- Ensure proper **hardware reset and initialization sequence** for W5500

- Check **PHY link status** before opening sockets

- Handle socket states (LISTEN, ESTABLISHED, CLOSE_WAIT) correctly

- Avoid blocking loops in STM32 main loop

- Use interrupt or RTOS for better task separation if needed

- Monitor buffer sizes when handling large data

### FAQ

**Q: Why use W5500 with STM32 instead of LwIP?**
A: W5500 offloads the TCP/IP stack to hardware, reducing STM32 CPU load and memory usage while simplifying firmware design.

**Q: How is W5500 connected to STM32?**
A: Through SPI interface (MISO, MOSI, SCK, CS), along with optional interrupt and reset pins.

**Q: What role does W5500 play in this system?**
A: It handles all Ethernet communication, including TCP/UDP processing and socket management.

**Q: Can beginners use STM32 + W5500?**
A: Yes. It is often easier than using LwIP because networking is handled by hardware, reducing software complexity.

**Q: TCP vs UDP on STM32 + W5500?**
A: TCP is used for reliable communication (e.g., MQTT), while UDP is better for low-latency or broadcast use cases.

### Source

- Original Article: <https://blog.csdn.net/dafurong/article/details/148143390>

- License: Not specified

### Tags

#W5500 #STM32 #Ethernet #TCP #UDP #SPI #EmbeddedSystems #IoT #MQTT #WIZnet

## STM32에서 W5500으로 안정적인 TCP/UDP 통신을 구축하는 방법은?

### Summary

이 프로젝트는 STM32 MCU와 WIZnet W5500 Ethernet 컨트롤러를 함께 사용해 안정적인 TCP/UDP 통신을 구현하는 방법을 보여줍니다. W5500은 하드웨어 TCP/IP 스택을 제공하므로 LwIP 같은 소프트웨어 스택이 필요하지 않습니다. 이 구조에서 STM32는 애플리케이션 로직을 담당하고, W5500은 네트워크 전송 엔진으로 동작하여 보다 예측 가능하고 오버헤드가 낮은 Ethernet 통신을 가능하게 합니다.

### What the Project Does

이 시스템은 STM32와 W5500을 조합해 **완전한 임베디드 Ethernet 통신 경로**를 구성합니다.

핵심 기능은 다음과 같습니다.

- STM32와 W5500 간 SPI 기반 통신

- 네트워크 설정(MAC, IP, subnet, gateway)

- TCP/UDP 소켓 생성 및 관리

- 데이터 송수신

- 연결 상태 모니터링

시스템 흐름은 다음과 같습니다.

STM32 → SPI → W5500 → Ethernet → Remote Host

주요 통신 방식은 두 가지입니다.

#### TCP Mode

- 연결 지향 방식

- 신뢰성 있는 전송

- 재전송은 W5500이 내부적으로 처리

- MQTT, HTTP, 원격 제어에 적합

#### UDP Mode

- 비연결 방식

- 더 낮은 지연

- 스트리밍, 브로드캐스트, 센서 버스트 전송에 적합

이 구조는 다음과 같은 분야에서 자주 사용됩니다.

- 산업용 IoT 장치

- 임베디드 게이트웨이

- 원격 모니터링 시스템

### Where WIZnet Fits

이 시스템에서 **W5500**은 STM32 옆에서 동작하는 전용 **하드웨어 TCP/IP 오프로드 엔진**입니다.

#### W5500의 역할

- 하드웨어 기반 TCP/IP 스택(TOE) 처리

- 패킷 버퍼링과 재전송 관리

- 최대 **8개의 동시 소켓** 지원

#### STM32의 역할

- 애플리케이션 로직 실행

- SPI를 통해 W5500 제어

- 수신 데이터 처리 및 응답 생성

이 역할 분리가 중요한 이유는 분명합니다.

- STM32가 LwIP나 RTOS 네트워킹 작업을 직접 처리하지 않아도 됨

- CPU와 RAM 사용량을 크게 줄일 수 있음

- 네트워크 타이밍이 더 예측 가능해짐

**STM32 + LwIP** 구조와 비교하면 차이가 더 뚜렷합니다.

- LwIP는 메모리 할당과 RTOS 튜닝이 필요함

- 인터럽트와 네트워크 타이밍이 서로 영향을 줄 수 있음

- W5500은 펌웨어를 단순하게 만들고 안정성을 높이기 쉽습니다

### Implementation Notes

원문 글은 W5500의 통신 흐름을 설명하지만, 전체 저장소 형태의 검증된 프로젝트는 제공하지 않습니다.

아래 코드는 **WIZnet ioLibrary 기반의 개념적 통합 예시**이며, STM32에 맞춰 설명한 것입니다.

// Conceptual integration example based on WIZnet ioLibrary

#include "wizchip_conf.h"
#include "socket.h"

// SPI functions implemented using STM32 HAL
void spi_write(uint8_t data);
uint8_t spi_read(void);

void wizchip_spi_init(void) {
reg_wizchip_spi_cbfunc(spi_read, spi_write);
}

void network_init(void) {
uint8_t txsize[8] = {2,2,2,2,2,2,2,2};
uint8_t rxsize[8] = {2,2,2,2,2,2,2,2};

wizchip_init(txsize, rxsize);

wiz_NetInfo netinfo = {
.mac = {0x00,0x08,0xDC,0xAA,0xBB,0xCC},
.ip = {192,168,1,100},
.sn = {255,255,255,0},
.gw = {192,168,1,1}
};

wizchip_setnetinfo(&netinfo);
}

void tcp_server(void) {
socket(0, Sn_MR_TCP, 5000, 0);
listen(0);

while (1) {
if (getSn_SR(0) == SOCK_ESTABLISHED) {
uint8_t buf[128];
int len = recv(0, buf, sizeof(buf));

if (len > 0) {
send(0, buf, len); // echo back
}
}
}
}

이 예제가 중요한 이유는 다음과 같습니다.

- STM32가 SPI를 통해 W5500과 어떻게 연결되는지 보여줌

- **하드웨어 소켓 기반 네트워킹** 구조를 이해하기 쉬움

- LwIP에 비해 펌웨어 복잡도가 얼마나 줄어드는지 드러남

MQTT로 확장하는 경우에는 다음과 같이 볼 수 있습니다.

- STM32가 MQTT 클라이언트 로직을 실행

- W5500이 TCP 전송 계층을 담당

- 전체 TCP/IP 스택을 소프트웨어로 구현하지 않고도 클라우드 연결 가능

### Practical Tips / Pitfalls

- STM32에서 **SPI 설정(mode, speed, CS timing)** 을 먼저 정확히 확인해야 합니다.

- W5500의 **하드웨어 리셋과 초기화 순서**를 안정적으로 처리해야 합니다.

- 소켓을 열기 전에 **PHY link 상태**를 점검하는 편이 좋습니다.

- LISTEN, ESTABLISHED, CLOSE_WAIT 같은 **소켓 상태 처리**를 정확히 해야 합니다.

- STM32 메인 루프에서 블로킹 루프를 과도하게 사용하지 않는 편이 좋습니다.

- 필요하면 인터럽트 또는 RTOS를 이용해 작업을 분리할 수 있습니다.

- 큰 데이터를 다룰 때는 버퍼 크기와 송수신 처리량을 함께 점검해야 합니다.

### FAQ

**Q: 왜 STM32에서 LwIP 대신 W5500을 사용하나요?**
A: W5500이 TCP/IP 스택을 하드웨어로 오프로드하기 때문에 STM32의 CPU 부하와 메모리 사용량을 줄일 수 있습니다. 그 결과 펌웨어 구조가 더 단순해지고 유지보수도 쉬워집니다.

**Q: W5500은 STM32에 어떻게 연결하나요?**
A: 일반적으로 SPI 인터페이스를 사용합니다. MISO, MOSI, SCK, CS에 더해 필요하면 INT와 RESET 핀도 함께 연결합니다.

**Q: 이 시스템에서 W5500은 어떤 역할을 하나요?**
A: Ethernet 통신 전체를 담당합니다. TCP/UDP 처리와 소켓 관리까지 네트워크 전송 계층 역할을 수행합니다.

**Q: 초보자도 STM32 + W5500을 사용할 수 있나요?**
A: 가능합니다. 네트워킹이 하드웨어에서 처리되기 때문에 LwIP를 직접 다루는 것보다 진입 장벽이 낮은 편입니다. 기본적인 SPI와 임베디드 C 지식이 있으면 충분히 시작할 수 있습니다.

**Q: STM32 + W5500에서 TCP와 UDP는 언제 각각 쓰나요?**
A: TCP는 MQTT처럼 신뢰성 있는 통신이 필요한 경우에 적합합니다. UDP는 더 낮은 지연이나 브로드캐스트가 중요한 경우에 적합합니다.

### Source

- Original Article: <https://blog.csdn.net/dafurong/article/details/148143390>

- License: 명시되지 않음

### Tags

#W5500 #STM32 #Ethernet #TCP #UDP #SPI #EmbeddedSystems #IoT #MQTT #WIZnet

---

Source: https://maker.wiznet.io/chen/projects/how-to-build-reliable-tcp-udp-communication-with-w5500-on-stm32/
