How to Implement DHCP Firmware with W5500 on STC32G144K246?
This project shows how an STC32G144K246 microcontroller can obtain an IP address automatically through DHCP using the WIZnet W5500 Ethernet controller.
How to Implement DHCP Firmware with W5500 on STC32G144K246?
Summary
This project shows how an STC32G144K246 microcontroller can obtain an IP address automatically through DHCP using the WIZnet W5500 Ethernet controller. In this architecture, the STC32G144K246 runs the application firmware and DHCP control flow, while the W5500 provides wired Ethernet connectivity through its hardware TCP/IP stack, SPI interface, socket engine, MAC/PHY, and internal packet buffers.
What the Project Does
The original article is part of an STC32G144K246 learning series and focuses on DHCP-based IP assignment with W5500. Its stated learning goals are to explain DHCP, describe the four DHCP stages, and write DHCP code for automatic network configuration. The visible article content introduces DHCP as the mechanism that assigns IP address, subnet mask, gateway, and DNS information automatically, instead of requiring static manual configuration.
The data flow is straightforward. The STC32G144K246 controls the W5500 over SPI. After the Ethernet link is available, the firmware starts a DHCP negotiation. The DHCP transaction follows the standard DORA sequence: Discover, Offer, Request, and Acknowledge. Once the lease is accepted, the firmware stores the assigned network parameters and can proceed to TCP or UDP application communication.
This is useful for general embedded networking because the device can be moved between routers, test benches, classrooms, and development networks without recompiling firmware for each static IP environment.
Where WIZnet Fits
The WIZnet product used here is the W5500. It sits between the STC32G144K246 MCU and the Ethernet network.
The W5500 matters because it is not just a PHY. It includes a hardwired TCP/IP stack, embedded 10/100 Ethernet MAC/PHY, SPI interface up to 80 MHz, 32 KB internal TX/RX buffer memory, and support for eight independent sockets.
For a small MCU firmware project, this changes the software boundary. The STC32G144K246 does not need to run a full software Ethernet MAC driver plus LwIP-style TCP/IP stack. Instead, the firmware mainly needs stable SPI access, W5500 register control, socket setup, DHCP state handling, and timeout recovery. That is a better fit when RAM, Flash, interrupt latency, and debugging time are more constrained than raw network-stack flexibility.
Implementation Notes
The original CSDN article is partially paywalled in the accessible page view, so the full source code could not be verified line by line. Because of that, the following is not copied from the article and should not be treated as the author’s exact code.
Conceptual integration example based on WIZnet ioLibrary:
uint8_t tx_size[8] = {2,2,2,2,2,2,2,2};
uint8_t rx_size[8] = {2,2,2,2,2,2,2,2};
wizchip_init(tx_size, rx_size);
wiz_NetInfo netinfo = {
.mac = {0x00, 0x08, 0xDC, 0x11, 0x22, 0x33},
.dhcp = NETINFO_DHCP
};
wizchip_setnetinfo(&netinfo);This initialization step allocates the W5500 socket buffers and marks the network configuration mode as DHCP. In a real STC32G144K246 port, the important firmware work is below this layer: implementing SPI read/write routines, chip-select control, reset timing, delay functions, and an accurate timer tick for DHCP timeouts.
Conceptual DHCP loop based on WIZnet ioLibrary:
DHCP_init(0, dhcp_buffer);
while (1) {
int state = DHCP_run();
if (state == DHCP_IP_LEASED) {
getIPfromDHCP(netinfo.ip);
getGWfromDHCP(netinfo.gw);
getSNfromDHCP(netinfo.sn);
getDNSfromDHCP(netinfo.dns);
wizchip_setnetinfo(&netinfo);
break;
}
}This loop represents the firmware responsibility: keep the DHCP state machine running until a valid lease is obtained, then copy the assigned IP, gateway, subnet mask, and DNS server into the W5500 network information structure. In production firmware, this loop should also handle timeout, lease renewal, link-down recovery, and fallback to a known static IP only when that behavior is explicitly required.
Compared with an LwIP implementation, the firmware is smaller in scope. With LwIP, the MCU usually owns the network interface driver, memory pools, TCP/IP timers, packet buffers, and protocol processing. With W5500, the MCU controls a hardware socket interface and uses the W5500 for the lower network transport workload. The trade-off is that W5500 gives less low-level protocol customization than LwIP, but it reduces the amount of network stack code that must be ported, tuned, and debugged on the MCU.
Practical Tips / Pitfalls
- Verify SPI mode and timing first. W5500 supports SPI mode 0 and 3, but firmware bugs often come from chip-select timing, wrong CPOL/CPHA, or unstable software SPI delays.
- Use a unique MAC address. DHCP may fail or produce unstable behavior if multiple boards share the same MAC address on one LAN.
- Treat DHCP as a state machine, not a blocking delay. The firmware should continue calling the DHCP handler and maintain a correct periodic timer.
- Check the PHY link before blaming DHCP. No link, bad cable, wrong magnetics, or unstable module power will look like a DHCP timeout.
- Reserve enough buffer space for DHCP and later sockets. The W5500 has 32 KB internal buffer memory, but the allocation across sockets should match the application traffic pattern.
- Add recovery logic for lease renewal and router restart. Embedded nodes are often left running longer than the development router.
- Keep watchdog behavior in mind. DHCP discovery can take longer than a normal control-loop iteration, so the watchdog should be serviced safely during network acquisition.
FAQ
Q: Why use W5500 for DHCP on STC32G144K246?
A: W5500 provides hardware TCP/IP offload, an embedded MAC/PHY, internal packet buffers, and socket-level operation over SPI. For STC32G144K246 firmware, this reduces the need to port and tune a full software TCP/IP stack just to obtain an IP address and start Ethernet communication.
Q: How does W5500 connect to the STC32G144K246?
A: It connects through SPI, using SCK, MOSI, MISO, chip-select, reset, power, and ground. Firmware must provide the low-level SPI read/write callbacks, chip-select control, reset sequence, and delay/timer functions before DHCP can work reliably.
Q: What role does W5500 play in this DHCP project?
A: W5500 is the Ethernet interface and hardware network engine. The STC32G144K246 runs the firmware logic and DHCP state handling, while W5500 handles Ethernet packet transfer, socket buffering, MAC/PHY operation, and hardware-assisted TCP/IP functions.
Q: Can beginners follow this project?
A: Yes, but it is not a pure “copy and run” networking exercise. A beginner should already understand GPIO, SPI, MCU timers, basic IP addressing, and serial debugging. The most common learning curve is not DHCP theory, but getting the W5500 SPI driver and link status stable first.
Q: How does W5500 compare with LwIP for this use case?
A: W5500 is simpler when the goal is reliable embedded Ethernet with limited MCU resources. LwIP is more flexible and can support deeper protocol customization, but it requires more RAM, more porting work, network-interface integration, timer management, and packet-buffer tuning. For a DHCP client on an STC32G144K246-class MCU, W5500 keeps the firmware focused on device logic instead of full network-stack maintenance.
Source
Original article: CSDN, “[STC32G144K246入门第九步] 使用W5500进行DHCP自动获取IP” by 单片有机机.
License: Not clearly stated on the accessible page.
Reference: WIZnet W5500 official product and documentation pages for hardware TCP/IP stack, SPI, buffer, and socket specifications.
Tags
#W5500 #WIZnet #STC32G144K246 #DHCP #Ethernet #SPI #EmbeddedFirmware #TCPIP #GeneralEmbeddedNetworking #LwIP
STC32G144K246에서 W5500으로 DHCP 펌웨어를 구현하는 방법은?
Summary
이 프로젝트는 STC32G144K246 마이크로컨트롤러가 WIZnet W5500 이더넷 컨트롤러를 사용해 DHCP로 IP 주소를 자동 할당받는 방법을 보여줍니다. 이 구조에서 STC32G144K246은 애플리케이션 펌웨어와 DHCP 제어 흐름을 담당하고, W5500은 하드웨어 TCP/IP 스택, SPI 인터페이스, 소켓 엔진, MAC/PHY, 내부 패킷 버퍼를 통해 유선 이더넷 연결을 담당합니다.
What the Project Does
원문은 STC32G144K246 입문 시리즈의 일부이며, W5500을 사용한 DHCP 기반 IP 할당에 초점을 둡니다. 글의 학습 목표는 DHCP의 개념, DHCP의 네 단계 동작 흐름, 그리고 자동 네트워크 설정을 위한 DHCP 코드 작성입니다.
데이터 흐름은 단순합니다. STC32G144K246은 SPI를 통해 W5500을 제어합니다. 이더넷 링크가 준비되면 펌웨어가 DHCP 협상을 시작합니다. DHCP 트랜잭션은 일반적인 DORA 흐름, 즉 Discover, Offer, Request, Acknowledge 순서로 진행됩니다. 임대가 승인되면 펌웨어는 할당된 네트워크 파라미터를 저장하고 TCP 또는 UDP 애플리케이션 통신을 시작할 수 있습니다.
이 방식은 일반 임베디드 네트워킹에 유용합니다. 장치를 라우터, 테스트 벤치, 교육용 네트워크, 개발 환경 사이에서 이동해도 매번 정적 IP를 다시 컴파일할 필요가 없기 때문입니다.
Where WIZnet Fits
이 프로젝트에서 사용되는 WIZnet 제품은 W5500입니다. W5500은 STC32G144K246 MCU와 이더넷 네트워크 사이에 위치합니다.
W5500은 단순한 PHY가 아닙니다. 하드웨어 TCP/IP 스택, 내장 10/100 이더넷 MAC/PHY, 최대 80 MHz SPI 인터페이스, 32 KB 내부 TX/RX 버퍼 메모리, 8개의 독립 소켓을 제공합니다.
소형 MCU 펌웨어 프로젝트에서는 이 점이 소프트웨어 경계를 바꿉니다. STC32G144K246이 전체 이더넷 MAC 드라이버와 LwIP 같은 소프트웨어 TCP/IP 스택을 직접 실행할 필요가 없습니다. 대신 펌웨어는 안정적인 SPI 접근, W5500 레지스터 제어, 소켓 설정, DHCP 상태 처리, 타임아웃 복구에 집중하면 됩니다. RAM, Flash, 인터럽트 지연, 디버깅 시간이 제한적인 MCU 환경에서는 이 구조가 더 현실적입니다.
Implementation Notes
접근 가능한 CSDN 페이지에서는 원문 전체 코드가 완전히 공개되어 있지 않아, 소스 코드를 줄 단위로 검증할 수 없었습니다. 따라서 아래 코드는 원문에서 복사한 코드가 아니며, 작성자의 실제 코드로 간주해서는 안 됩니다.
Conceptual integration example based on WIZnet ioLibrary:
uint8_t tx_size[8] = {2,2,2,2,2,2,2,2};
uint8_t rx_size[8] = {2,2,2,2,2,2,2,2};
wizchip_init(tx_size, rx_size);
wiz_NetInfo netinfo = {
.mac = {0x00, 0x08, 0xDC, 0x11, 0x22, 0x33},
.dhcp = NETINFO_DHCP
};
wizchip_setnetinfo(&netinfo);이 초기화 단계는 W5500의 소켓 버퍼를 할당하고 네트워크 설정 모드를 DHCP로 지정합니다. 실제 STC32G144K246 포팅에서 중요한 작업은 이 코드 아래 계층에 있습니다. SPI read/write 루틴, chip-select 제어, reset 타이밍, delay 함수, DHCP 타임아웃을 위한 정확한 타이머 tick을 구현해야 합니다.
Conceptual DHCP loop based on WIZnet ioLibrary:
DHCP_init(0, dhcp_buffer);
while (1) {
int state = DHCP_run();
if (state == DHCP_IP_LEASED) {
getIPfromDHCP(netinfo.ip);
getGWfromDHCP(netinfo.gw);
getSNfromDHCP(netinfo.sn);
getDNSfromDHCP(netinfo.dns);
wizchip_setnetinfo(&netinfo);
break;
}
}이 루프는 펌웨어가 담당해야 하는 핵심 책임을 나타냅니다. 유효한 DHCP 임대를 받을 때까지 DHCP 상태 머신을 계속 실행하고, 할당된 IP 주소, 게이트웨이, 서브넷 마스크, DNS 서버 정보를 W5500 네트워크 정보 구조체에 복사합니다. 실제 제품 펌웨어에서는 타임아웃, 임대 갱신, 링크 다운 복구, 라우터 재시작 대응, 필요 시 정적 IP fallback까지 고려해야 합니다.
LwIP 구현과 비교하면 펌웨어 범위가 줄어듭니다. LwIP를 사용할 경우 MCU는 네트워크 인터페이스 드라이버, 메모리 풀, TCP/IP 타이머, 패킷 버퍼, 프로토콜 처리를 직접 관리해야 합니다. W5500을 사용하면 MCU는 하드웨어 소켓 인터페이스를 제어하고, 낮은 계층의 네트워크 전송 작업은 W5500에 맡깁니다. 대신 W5500은 LwIP보다 저수준 프로토콜 커스터마이징 자유도는 낮습니다. 그러나 MCU에서 네트워크 스택을 포팅하고 튜닝하고 디버깅해야 하는 부담은 줄어듭니다.
Practical Tips / Pitfalls
- SPI 모드와 타이밍을 먼저 검증해야 합니다. W5500은 SPI mode 0과 mode 3을 지원하지만, 실제 문제는 chip-select 타이밍, 잘못된 CPOL/CPHA, 불안정한 소프트웨어 SPI delay에서 자주 발생합니다.
- 고유한 MAC 주소를 사용해야 합니다. 같은 LAN에 동일한 MAC 주소를 가진 보드가 여러 개 있으면 DHCP가 실패하거나 네트워크 동작이 불안정해질 수 있습니다.
- DHCP를 단순 blocking delay로 처리하지 말고 상태 머신으로 다뤄야 합니다. 펌웨어는 DHCP 핸들러를 계속 호출하면서 정확한 주기 타이머를 유지해야 합니다.
- DHCP를 의심하기 전에 PHY link를 확인해야 합니다. 링크 없음, 불량 케이블, 잘못된 magnetics, 불안정한 모듈 전원은 모두 DHCP 타임아웃처럼 보일 수 있습니다.
- DHCP와 이후 소켓 통신을 위한 버퍼 공간을 적절히 예약해야 합니다. W5500은 32 KB 내부 버퍼 메모리를 제공하지만, 소켓별 할당은 애플리케이션 트래픽 패턴에 맞춰야 합니다.
- 임대 갱신과 라우터 재시작에 대한 복구 로직을 추가해야 합니다. 임베디드 노드는 개발용 라우터보다 훨씬 오래 켜져 있는 경우가 많습니다.
- Watchdog 동작을 고려해야 합니다. DHCP discovery는 일반 제어 루프보다 오래 걸릴 수 있으므로, 네트워크 획득 중에도 watchdog을 안전하게 갱신해야 합니다.
FAQ
Q: STC32G144K246에서 DHCP 구현에 W5500을 사용하는 이유는 무엇인가요?
A: W5500은 하드웨어 TCP/IP 오프로딩, 내장 MAC/PHY, 내부 패킷 버퍼, SPI 기반 소켓 제어를 제공합니다. STC32G144K246 펌웨어 입장에서는 IP 주소를 받고 이더넷 통신을 시작하기 위해 전체 소프트웨어 TCP/IP 스택을 포팅하고 튜닝할 필요가 줄어듭니다.
Q: W5500은 STC32G144K246에 어떻게 연결되나요?
A: W5500은 SPI로 연결됩니다. SCK, MOSI, MISO, chip-select, reset, 전원, ground가 필요합니다. DHCP가 안정적으로 동작하려면 저수준 SPI read/write callback, chip-select 제어, reset 시퀀스, delay 및 timer 함수가 먼저 제대로 구현되어야 합니다.
Q: 이 프로젝트에서 W5500은 어떤 역할을 하나요?
A: W5500은 이더넷 인터페이스이자 하드웨어 네트워크 엔진입니다. STC32G144K246은 펌웨어 로직과 DHCP 상태 처리를 실행하고, W5500은 이더넷 패킷 전송, 소켓 버퍼링, MAC/PHY 동작, 하드웨어 기반 TCP/IP 기능을 담당합니다.
Q: 초보자도 따라할 수 있나요?
A: 가능하지만 단순한 복사-실행형 네트워크 예제는 아닙니다. GPIO, SPI, MCU 타이머, 기본 IP 주소 체계, 시리얼 디버깅에 대한 이해가 필요합니다. 가장 흔한 난관은 DHCP 이론이 아니라 W5500 SPI 드라이버와 링크 상태를 안정화하는 과정입니다.
Q: 이 용도에서 W5500은 LwIP와 어떻게 다르나요?
A: W5500은 제한된 MCU 자원에서 안정적인 임베디드 이더넷을 구현할 때 더 단순합니다. LwIP는 더 유연하고 깊은 프로토콜 커스터마이징이 가능하지만, 더 많은 RAM, 포팅 작업, 네트워크 인터페이스 통합, 타이머 관리, 패킷 버퍼 튜닝이 필요합니다. STC32G144K246급 MCU에서 DHCP 클라이언트를 구현하는 경우, W5500은 펌웨어가 전체 네트워크 스택 유지보수보다 장치 로직에 집중할 수 있게 합니다.
Source
Original article: CSDN, “[STC32G144K246入门第九步] 使用W5500进行DHCP自动获取IP” by 单片有机机.
License: 접근 가능한 페이지에서 명확히 확인되지 않았습니다.
Reference: WIZnet W5500 공식 제품 및 문서 페이지의 하드웨어 TCP/IP 스택, SPI, 버퍼, 소켓 사양.
Tags
#W5500 #WIZnet #STC32G144K246 #DHCP #Ethernet #SPI #EmbeddedFirmware #TCPIP #GeneralEmbeddedNetworking #LwIP
