Wiznet makers

Arnold

Published May 29, 2026 ©

34 UCC

1 VAR

0 Contests

0 Followers

0 Following

Original Link

How to Build a TCP Client with W5500 on STC32G144K246?

This project demonstrates how to use software SPI on the STC32G144K246 microcontroller to drive the WIZnet W5500 Ethernet controller as a TCP client.

COMPONENTS
PROJECT DESCRIPTION

How to Build a TCP Client with W5500 on STC32G144K246?

Summary

This project demonstrates how to use software SPI on the STC32G144K246 microcontroller to drive the WIZnet W5500 Ethernet controller as a TCP client. The MCU provides GPIO-based SPI control and application logic, while the W5500 handles Ethernet connectivity, hardware TCP/IP processing, socket management, and packet buffering for reliable wired communication in industrial embedded systems.

What the Project Does

The original article is part of an STC32G144K246 learning series and focuses on driving the W5500 through software SPI to implement TCP client communication. The stated learning goals are to understand the W5500 module, TCP communication, TCP client behavior, and how to write a TCP client communication program.

The system architecture is direct. The STC32G144K246 uses GPIO pins to emulate SPI signals and communicate with the W5500. After the W5500 is initialized with network parameters, the firmware opens a hardware socket, configures it for TCP client mode, connects to a remote server IP and port, then sends or receives application data through the W5500 socket buffer.

This is relevant to industrial IoT because many control nodes, meters, gateways, and local monitoring devices need stable Ethernet communication but may not have a dedicated hardware SPI peripheral available on the chosen pins. Software SPI gives the firmware designer more pin-routing flexibility, while W5500 keeps the TCP/IP workload out of the main MCU firmware.

Where WIZnet Fits

The WIZnet product used in this project is the W5500. It acts as the Ethernet controller and hardware TCP/IP engine between the STC32G144K246 and the wired LAN.

The source article describes the W5500 as a WIZnet hardwired TCP/IP Ethernet controller intended to provide a simple and reliable Ethernet interface for MCU projects. It also lists key characteristics relevant to this design: SPI host interface, TCP/UDP/ICMP/IPv4/ARP/IGMP/PPPoE support, 8 independent hardware sockets, 32 KB internal TX/RX buffer memory, 10/100 Mbps Ethernet, and industrial temperature suitability.

In this firmware design, software SPI is the control path and W5500 is the network execution layer. The MCU toggles SCK, MOSI, MISO, and chip-select through GPIO. The W5500 receives commands and data over that interface, then handles TCP connection state, socket buffering, packet transmission, retransmission behavior, and Ethernet framing internally.

That division is important in industrial systems. The MCU can remain focused on I/O scanning, device state, protocol framing, alarms, and watchdog handling, instead of spending RAM and CPU time on a full software TCP/IP stack. The trade-off is that software SPI must be carefully timed and tested, because unstable bit-banged SPI will make the W5500 look unreliable even when the network side is correct.

Implementation Notes

The accessible part of the CSDN article confirms the project topic, W5500 role, and key W5500 specifications, but the full implementation code is not visible in the public page view. Therefore, the following code is not copied from the article and should be treated as a conceptual integration example based on WIZnet ioLibrary-style socket operation.

Conceptual integration example based on WIZnet ioLibrary:

 
#define W5500_CS_LOW()    gpio_write(W5500_CS_PORT, W5500_CS_PIN, 0)
#define W5500_CS_HIGH()   gpio_write(W5500_CS_PORT, W5500_CS_PIN, 1)

static uint8_t soft_spi_transfer(uint8_t data)
{
    uint8_t rx = 0;

    for (uint8_t i = 0; i < 8; i++) {
        gpio_write(W5500_MOSI_PORT, W5500_MOSI_PIN, data & 0x80);
        data <<= 1;

        gpio_write(W5500_SCK_PORT, W5500_SCK_PIN, 1);
        rx <<= 1;
        if (gpio_read(W5500_MISO_PORT, W5500_MISO_PIN)) {
            rx |= 0x01;
        }
        gpio_write(W5500_SCK_PORT, W5500_SCK_PIN, 0);
    }

    return rx;
}
 

This software SPI routine represents the lowest layer of the port. It controls MOSI before the clock edge, samples MISO during the active clock phase, and returns one received byte for every transmitted byte. In a real STC32G144K246 firmware project, the clock polarity, clock phase, GPIO speed, and delay margin must match the W5500 SPI timing requirements.

Conceptual integration example based on WIZnet ioLibrary:

 
static void w5500_write_byte(uint8_t byte)
{
    soft_spi_transfer(byte);
}

static uint8_t w5500_read_byte(void)
{
    return soft_spi_transfer(0xFF);
}

void w5500_spi_select(void)
{
    W5500_CS_LOW();
}

void w5500_spi_deselect(void)
{
    W5500_CS_HIGH();
}
 

This callback layer is what connects the bit-banged SPI driver to the W5500 register and socket access functions. The chip-select line must remain stable for the full W5500 SPI transaction. If chip-select toggles between address, control, and data bytes, register reads and socket writes will fail intermittently.

Conceptual integration example based on WIZnet ioLibrary:

 
#define SOCK_TCP_CLIENT  0
#define SERVER_PORT      5000

uint8_t server_ip[4] = {192, 168, 1, 100};
uint8_t message[] = "STC32G144K246 W5500 TCP client\r\n";

socket(SOCK_TCP_CLIENT, Sn_MR_TCP, 3000, 0);

if (connect(SOCK_TCP_CLIENT, server_ip, SERVER_PORT) == SOCK_OK) {
    send(SOCK_TCP_CLIENT, message, sizeof(message) - 1);
}

disconnect(SOCK_TCP_CLIENT);
close(SOCK_TCP_CLIENT);
 

This socket flow shows the main TCP client sequence. The firmware opens one W5500 socket in TCP mode, connects to a known server endpoint, sends application data, then disconnects and closes the socket. In an industrial IoT node, this same structure can be used for periodic status upload, alarm reporting, local controller communication, or gateway-to-server telemetry.

The reason this code exists in the system is to keep network behavior deterministic and bounded. Software SPI gives the STC32G144K246 control over pin placement, while the W5500 socket engine turns the firmware operation into a small sequence of register and buffer transactions instead of a full TCP/IP stack implementation.

Practical Tips / Pitfalls

  • Validate software SPI before testing TCP. Read a stable W5500 register such as the version register first; socket debugging is wasted effort if byte transfer is unreliable.
  • Keep chip-select timing strict. A W5500 SPI frame depends on address, control, and data phases staying within the same selected transaction.
  • Use short wires and clean grounding. Bit-banged SPI is more sensitive to edge quality, especially when jumper wires, relay loads, or industrial power supplies are nearby.
  • Start with a conservative software SPI speed. After the TCP client is stable, increase the clock rate and retest under temperature, cable, and power variation.
  • Separate link failure from socket failure. Check PHY link status before assuming the TCP server, port, or socket state is wrong.
  • Allocate W5500 buffers according to traffic pattern. A simple TCP client may only need one active socket, but telemetry bursts and local command channels may require different RX/TX sizing.
  • Add reconnect logic. Industrial nodes must handle server restart, cable removal, switch reboot, duplicate IP problems, and watchdog recovery without manual reset.

FAQ

Q: Why use W5500 for a software SPI TCP client on STC32G144K246?
A: W5500 provides the Ethernet MAC/PHY, hardware TCP/IP stack, socket engine, and internal packet buffers. This lets the STC32G144K246 use GPIO-based SPI for network control while avoiding the RAM, timer, and packet-buffer complexity of a full software network stack.

Q: How does W5500 connect to the STC32G144K246 in this project?
A: It connects through an SPI-style interface implemented in firmware. The MCU drives SCK, MOSI, MISO, chip-select, reset, power, and ground; because the SPI is software-generated, the GPIO timing and chip-select sequence are part of the network driver’s correctness.

Q: What role does W5500 play in this TCP client system?
A: W5500 is the wired Ethernet interface and TCP socket processor. The STC32G144K246 decides when to connect, send, receive, and close, while W5500 executes the Ethernet and TCP socket operations behind those commands.

Q: Can beginners follow this project?
A: It is suitable for developers who already understand GPIO, SPI timing, TCP client/server basics, and serial debugging. The hardest part is usually not opening the TCP socket; it is proving that the software SPI layer is stable enough for repeated W5500 register and buffer access.

Q: Why is this useful for Industrial IoT?
A: Industrial nodes often need wired communication, predictable recovery, and long uptime. W5500 provides a hardware Ethernet path with socket-level control, while software SPI allows flexible MCU pin assignment when the board layout or peripheral allocation is constrained.

Source

Original article: CSDN, “[STC32G144K246入门第八步] 软件SPI驱动W5500进行TCP客户端通信” by 单片有机机. The accessible page confirms the project topic, learning goals, and W5500 feature summary.

License: Not clearly stated on the accessible page.

Tags

#W5500 #WIZnet #STC32G144K246 #SoftwareSPI #TCPClient #Ethernet #IndustrialIoT #EmbeddedFirmware #SocketProgramming #HardwiredTCPIP

 

STC32G144K246에서 W5500으로 TCP 클라이언트를 구현하는 방법은?

Summary

이 프로젝트는 STC32G144K246 마이크로컨트롤러에서 소프트웨어 SPI로 WIZnet W5500 이더넷 컨트롤러를 구동해 TCP 클라이언트를 구현하는 방법을 보여줍니다. MCU는 GPIO 기반 SPI 제어와 애플리케이션 로직을 담당하고, W5500은 산업용 임베디드 시스템에서 안정적인 유선 통신을 위해 이더넷 연결, 하드웨어 TCP/IP 처리, 소켓 관리, 패킷 버퍼링을 담당합니다.

What the Project Does

원문은 STC32G144K246 입문 시리즈의 일부이며, 소프트웨어 SPI로 W5500을 구동해 TCP 클라이언트 통신을 구현하는 데 초점을 둡니다. 학습 목표는 W5500 모듈 이해, TCP 통신 이해, TCP 클라이언트 동작 이해, TCP 클라이언트 통신 프로그램 작성입니다.

시스템 구조는 직접적입니다. STC32G144K246은 GPIO 핀으로 SPI 신호를 에뮬레이션하여 W5500과 통신합니다. W5500에 네트워크 파라미터를 설정한 뒤, 펌웨어는 하드웨어 소켓을 열고 TCP 클라이언트 모드로 설정합니다. 이후 원격 서버 IP와 포트에 연결하고, W5500의 소켓 버퍼를 통해 애플리케이션 데이터를 송수신합니다.

이 구조는 산업용 IoT에 적합합니다. 제어 노드, 계측기, 게이트웨이, 로컬 모니터링 장치는 안정적인 이더넷 통신이 필요하지만, 선택한 핀에 하드웨어 SPI 주변장치를 항상 배치할 수 있는 것은 아닙니다. 소프트웨어 SPI는 핀 라우팅 유연성을 제공하고, W5500은 TCP/IP 처리 부담을 MCU 펌웨어에서 분리합니다.

Where WIZnet Fits

이 프로젝트에서 사용되는 WIZnet 제품은 W5500입니다. W5500은 STC32G144K246과 유선 LAN 사이에서 이더넷 컨트롤러이자 하드웨어 TCP/IP 엔진으로 동작합니다.

원문은 W5500을 MCU 프로젝트에 단순하고 안정적인 이더넷 인터페이스를 제공하기 위한 WIZnet의 하드와이어드 TCP/IP 이더넷 컨트롤러로 설명합니다. 이 설계와 관련된 주요 특징으로는 SPI 호스트 인터페이스, TCP/UDP/ICMP/IPv4/ARP/IGMP/PPPoE 지원, 8개의 독립 하드웨어 소켓, 32 KB 내부 TX/RX 버퍼 메모리, 10/100 Mbps 이더넷, 산업용 온도 대응이 있습니다.

이 펌웨어 구조에서 소프트웨어 SPI는 제어 경로이고, W5500은 네트워크 실행 계층입니다. MCU는 GPIO로 SCK, MOSI, MISO, chip-select를 토글합니다. W5500은 이 인터페이스를 통해 명령과 데이터를 받고, TCP 연결 상태, 소켓 버퍼링, 패킷 전송, 재전송 동작, 이더넷 프레이밍을 내부에서 처리합니다.

이 분리는 산업용 시스템에서 중요합니다. MCU는 I/O 스캔, 장치 상태, 프로토콜 프레이밍, 알람, watchdog 처리에 집중할 수 있고, 전체 소프트웨어 TCP/IP 스택에 RAM과 CPU 시간을 소비하지 않아도 됩니다. 단, 소프트웨어 SPI의 타이밍과 안정성은 반드시 검증해야 합니다. 비트뱅 방식 SPI가 불안정하면 네트워크 쪽이 정상이어도 W5500이 불안정한 것처럼 보일 수 있습니다.

Implementation Notes

접근 가능한 CSDN 페이지에서는 프로젝트 주제, W5500의 역할, 주요 W5500 사양은 확인할 수 있었지만, 전체 구현 코드는 공개 페이지에서 확인할 수 없었습니다. 따라서 아래 코드는 원문에서 복사한 것이 아니며, WIZnet ioLibrary 스타일 소켓 동작을 기준으로 한 개념적 통합 예시입니다.

Conceptual integration example based on WIZnet ioLibrary:

 
#define W5500_CS_LOW()    gpio_write(W5500_CS_PORT, W5500_CS_PIN, 0)
#define W5500_CS_HIGH()   gpio_write(W5500_CS_PORT, W5500_CS_PIN, 1)

static uint8_t soft_spi_transfer(uint8_t data)
{
    uint8_t rx = 0;

    for (uint8_t i = 0; i < 8; i++) {
        gpio_write(W5500_MOSI_PORT, W5500_MOSI_PIN, data & 0x80);
        data <<= 1;

        gpio_write(W5500_SCK_PORT, W5500_SCK_PIN, 1);
        rx <<= 1;
        if (gpio_read(W5500_MISO_PORT, W5500_MISO_PIN)) {
            rx |= 0x01;
        }
        gpio_write(W5500_SCK_PORT, W5500_SCK_PIN, 0);
    }

    return rx;
}
 

이 소프트웨어 SPI 루틴은 포팅의 최하위 계층을 나타냅니다. 클록 엣지 전에 MOSI를 제어하고, 활성 클록 구간에서 MISO를 샘플링하며, 전송한 1바이트마다 수신 1바이트를 반환합니다. 실제 STC32G144K246 펌웨어에서는 W5500 SPI 타이밍 요구사항에 맞게 클록 극성, 클록 위상, GPIO 속도, 지연 여유를 검증해야 합니다.

Conceptual integration example based on WIZnet ioLibrary:

 
static void w5500_write_byte(uint8_t byte)
{
    soft_spi_transfer(byte);
}

static uint8_t w5500_read_byte(void)
{
    return soft_spi_transfer(0xFF);
}

void w5500_spi_select(void)
{
    W5500_CS_LOW();
}

void w5500_spi_deselect(void)
{
    W5500_CS_HIGH();
}
 

이 callback 계층은 비트뱅 SPI 드라이버를 W5500 레지스터 및 소켓 접근 함수와 연결합니다. chip-select 라인은 하나의 W5500 SPI 트랜잭션 전체 동안 안정적으로 유지되어야 합니다. 주소, 제어, 데이터 바이트 사이에서 chip-select가 흔들리면 레지스터 읽기와 소켓 쓰기가 간헐적으로 실패할 수 있습니다.

Conceptual integration example based on WIZnet ioLibrary:

 
#define SOCK_TCP_CLIENT  0
#define SERVER_PORT      5000

uint8_t server_ip[4] = {192, 168, 1, 100};
uint8_t message[] = "STC32G144K246 W5500 TCP client\r\n";

socket(SOCK_TCP_CLIENT, Sn_MR_TCP, 3000, 0);

if (connect(SOCK_TCP_CLIENT, server_ip, SERVER_PORT) == SOCK_OK) {
    send(SOCK_TCP_CLIENT, message, sizeof(message) - 1);
}

disconnect(SOCK_TCP_CLIENT);
close(SOCK_TCP_CLIENT);
 

이 소켓 흐름은 TCP 클라이언트의 주요 순서를 보여줍니다. 펌웨어는 W5500 소켓 하나를 TCP 모드로 열고, 지정된 서버 엔드포인트에 연결한 뒤, 애플리케이션 데이터를 전송하고, 연결을 해제한 다음 소켓을 닫습니다. 산업용 IoT 노드에서는 이 구조를 주기적 상태 업로드, 알람 보고, 로컬 컨트롤러 통신, 게이트웨이-서버 텔레메트리에 사용할 수 있습니다.

이 코드가 시스템에 필요한 이유는 네트워크 동작을 작고 예측 가능한 흐름으로 만들기 위해서입니다. 소프트웨어 SPI는 STC32G144K246이 핀 배치를 유연하게 제어할 수 있게 하고, W5500 소켓 엔진은 전체 TCP/IP 스택 구현 대신 레지스터와 버퍼 트랜잭션 중심의 펌웨어 구조를 가능하게 합니다.

Practical Tips / Pitfalls

  • TCP를 테스트하기 전에 소프트웨어 SPI를 먼저 검증해야 합니다. 예를 들어 W5500 version register처럼 안정적으로 읽을 수 있는 레지스터를 반복 읽어 확인하는 것이 좋습니다.
  • chip-select 타이밍을 엄격하게 유지해야 합니다. W5500 SPI 프레임은 주소, 제어, 데이터 단계가 하나의 선택된 트랜잭션 안에서 유지되어야 합니다.
  • 배선을 짧게 하고 ground를 안정적으로 구성해야 합니다. 비트뱅 SPI는 특히 점퍼선, 릴레이 부하, 산업용 전원 장치 주변에서 엣지 품질에 민감합니다.
  • 처음에는 보수적인 소프트웨어 SPI 속도로 시작해야 합니다. TCP 클라이언트가 안정화된 뒤 클록 속도를 올리고, 온도, 케이블, 전원 변동 조건에서 다시 테스트해야 합니다.
  • 링크 실패와 소켓 실패를 분리해서 봐야 합니다. TCP 서버, 포트, 소켓 상태를 의심하기 전에 PHY link 상태를 확인해야 합니다.
  • 트래픽 패턴에 맞게 W5500 버퍼를 할당해야 합니다. 단순 TCP 클라이언트는 활성 소켓 하나만 필요할 수 있지만, 텔레메트리 burst나 로컬 명령 채널이 있으면 RX/TX 크기를 다르게 잡아야 합니다.
  • 재연결 로직을 추가해야 합니다. 산업용 노드는 서버 재시작, 케이블 제거, 스위치 재부팅, IP 충돌, watchdog 복구를 수동 리셋 없이 처리해야 합니다.

FAQ

Q: STC32G144K246에서 소프트웨어 SPI TCP 클라이언트에 W5500을 사용하는 이유는 무엇인가요?
A: W5500은 이더넷 MAC/PHY, 하드웨어 TCP/IP 스택, 소켓 엔진, 내부 패킷 버퍼를 제공합니다. STC32G144K246은 GPIO 기반 SPI로 네트워크를 제어하면서도 전체 소프트웨어 네트워크 스택에 필요한 RAM, 타이머, 패킷 버퍼 관리 부담을 피할 수 있습니다.

Q: 이 프로젝트에서 W5500은 STC32G144K246에 어떻게 연결되나요?
A: W5500은 펌웨어로 구현한 SPI 스타일 인터페이스를 통해 연결됩니다. MCU는 SCK, MOSI, MISO, chip-select, reset, 전원, ground를 사용합니다. SPI가 소프트웨어로 생성되기 때문에 GPIO 타이밍과 chip-select 시퀀스 자체가 네트워크 드라이버의 정확성을 결정합니다.

Q: 이 TCP 클라이언트 시스템에서 W5500은 어떤 역할을 하나요?
A: W5500은 유선 이더넷 인터페이스이자 TCP 소켓 처리기입니다. STC32G144K246은 언제 연결하고, 송신하고, 수신하고, 닫을지를 결정하며, W5500은 그 명령 뒤에서 이더넷 및 TCP 소켓 동작을 실행합니다.

Q: 초보자도 따라할 수 있나요?
A: GPIO, SPI 타이밍, TCP 클라이언트/서버 기본 개념, 시리얼 디버깅을 이미 이해한 개발자에게 적합합니다. 가장 어려운 부분은 TCP 소켓을 여는 것이 아니라, 반복적인 W5500 레지스터 및 버퍼 접근에 충분히 안정적인 소프트웨어 SPI 계층을 검증하는 것입니다.

Q: 왜 이 구조가 산업용 IoT에 유용한가요?
A: 산업용 노드는 유선 통신, 예측 가능한 복구, 긴 가동 시간이 필요한 경우가 많습니다. W5500은 소켓 레벨 제어가 가능한 하드웨어 이더넷 경로를 제공하고, 소프트웨어 SPI는 보드 레이아웃이나 주변장치 할당이 제한된 경우에도 MCU 핀 배치를 유연하게 해줍니다.

Source

Original article: CSDN, “[STC32G144K246入门第八步] 软件SPI驱动W5500进行TCP客户端通信” by 单片有机机. 접근 가능한 페이지에서 프로젝트 주제, 학습 목표, W5500 기능 요약을 확인할 수 있었습니다.

License: 접근 가능한 페이지에서 명확히 확인되지 않았습니다.

Tags

#W5500 #WIZnet #STC32G144K246 #SoftwareSPI #TCPClient #Ethernet #IndustrialIoT #EmbeddedFirmware #SocketProgramming #HardwiredTCPIP

Documents
Comments Write