Wiznet makers

josephsr

Published July 04, 2026 ©

135 UCC

13 WCC

13 VAR

0 Contests

0 Followers

0 Following

Original Link

(temp) STM32F103 W5500 MQTT Gateway for CAN and RS485 Motor Control

An STM32F103 gateway uses W5500 Ethernet and MQTT to receive remote motor commands, then routes them to stepper motor drivers through CAN or RS485/Modbus.

COMPONENTS
PROJECT DESCRIPTION

Project Overview

This project implements a gateway based on STM32F103. The repository description states that it uses a W5500 chip to build the network path, subscribes to motor control commands through MQTT, and forwards the commands to stepper motor driver boards through CAN or RS485 for remote motor control.

The repository is structured as an embedded firmware project, with directories such as App, Common, Core, Drivers, FreeRTOS, Interface, MDK-ARM, and docs. The main implementation is written mostly in C, with the repository language summary showing C as the dominant language.


Project Type

ItemDescription
Project typeEmbedded industrial gateway firmware
MCUSTM32F103C8T6 / STM32F103C(8-B)Tx
Network interfaceW5500 Ethernet Controller through SPI
Network protocolMQTT over TCP
Field-side interfacesCAN and RS485/Modbus
RTOSFreeRTOS
Main functionRemote stepper motor command reception, protocol selection, command forwarding, and status reporting

The STM32CubeMX .ioc file confirms the MCU target as STM32F103C8T6, with CAN, SPI2, USART1, and USART2 enabled. It also defines W5500-related GPIO labels for chip select and reset.


System Architecture

 
MQTT Broker / Host PC
        |
        | Ethernet TCP/MQTT
        |
W5500 Ethernet Controller
        |
        | SPI2
        |
STM32F103 Gateway Firmware
        |
        +-- MQTT Task
        |     - W5500 initialization
        |     - MQTT broker connection
        |     - Subscribe: gateway_pull
        |     - Publish: gateway_push
        |
        +-- Command Parser Task
        |     - JSON parsing
        |     - connection_type check
        |     - device_id / motor_start / motor_dir / motor_round extraction
        |
        +-- Modbus Task
        |     - RS485/Modbus motor control
        |     - coil/register write
        |     - speed readback
        |
        +-- CAN Task
              - CAN frame transmission
              - CAN response forwarding
 

The application creates four FreeRTOS tasks: MQTT, CmdParse, Modbus, and CAN. It also creates separate queues for MQTT receive, MQTT publish, Modbus command, and CAN command paths.


Operation Flow

  1. The MQTT task initializes the W5500 network interface, connects to the MQTT server, subscribes to gateway_pull, and publishes responses to gateway_push
  2. Incoming MQTT payloads are passed to the command parser through xQueue_MQTT_Rx
  3. The command parser parses JSON fields including connection_type, device_id, motor_start, motor_dir, and motor_round
  4. If connection_type is rs485, the command is sent to the Modbus queue. If it is can, the command is sent to the CAN queue. 
  5. The Modbus task writes motor start/direction values through coils, writes motor rotation count through a holding register, reads speed from input registers, and publishes speed reports back through MQTT. 
  6. The CAN task packs the command into a CAN data frame, uses device_id as the standard frame ID, waits for a response, and forwards the received payload to the MQTT publish queue. 

WIZnet Product Usage and Role

ItemAssessment
WIZnet productW5500 Ethernet Controller
Interface to MCUSPI2
System roleEthernet TCP/IP communication path for MQTT
Driver layerWIZnet ioLibrary-style W5500 driver and socket API
Application-level roleEnables MQTT broker connection, command subscription, and response publication

The Ethernet directory contains W5500-related driver files such as W5500/w5500.c, W5500/w5500.h, socket.c, socket.h, wizchip_conf.c, and wizchip_conf.h.

Int_MQTT.c explicitly initializes Ethernet, creates a socket-style network object, connects to the MQTT server at port 1883, initializes the MQTT client, and subscribes to gateway_pull.

The W5500 driver file identifies itself as a W5500 HAL Interface and references WIZnet’s ioLibrary driver history and copyright. The same file implements WIZCHIP read/write operations over SPI, confirming that the W5500 is controlled through SPI register access.


TOE Usage

TOE Usage: Yes, through W5500 hardware socket operation.

This project does not use a software TCP/IP stack such as lwIP for Ethernet communication. The MQTT path is built over WIZnet-style socket APIs, and the lower Ethernet layer includes W5500 register-level SPI access and socket command handling. Int_MQTT.c comments describe MQTT initialization as “socket programming,” using NewNetwork() and ConnectNetwork() before MQTT client initialization.

The socket implementation controls WIZnet socket registers and commands such as Sn_MR_TCP, Sn_CR_CONNECT, Sn_CR_SEND, and Sn_CR_RECV, which indicates use of the W5500 hardware TCP/IP engine rather than a host-side TCP/IP stack.


Hybrid Network Assessment

Hybrid Network: No.

The project combines wired Ethernet with CAN and RS485/Modbus fieldbus interfaces. However, no Wi-Fi or other wireless network path is confirmed in the repository. Therefore, it should not be classified as a wired/wireless hybrid network system.

A more accurate description is:

 
Ethernet-to-CAN/RS485 industrial gateway
 

Strengths

StrengthDetails
Clear gateway roleMQTT commands are converted into field-side CAN or RS485/Modbus control messages.
Practical protocol bridgeThe project connects IP networking with common industrial control buses.
W5500-based EthernetThe network path is offloaded through W5500 socket operation, reducing MCU-side TCP/IP stack burden.
RTOS task separationMQTT, command parsing, Modbus, and CAN are separated into FreeRTOS tasks and queues.
Debugging documentationThe repository includes a FreeRTOS troubleshooting document covering heap usage, stack usage, CAN blocking, and task starvation.

The debugging document records practical constraints such as heap shortage, stack overflow risk from debug_printf, CAN initialization blocking, and starvation caused by a polling MQTT task without vTaskDelay().


Limitations

LimitationDetails
Fixed network configurationIP address, gateway, subnet mask, MAC address, and MQTT server IP are hard-coded in Int_MQTT.c.
Small MQTT buffersMQTT send/read buffers are defined as 128 bytes, limiting payload size.
Simple protocol selectionRouting depends on the JSON field connection_type with values such as rs485 or can; broader protocol negotiation is not shown.
Limited validation pathMessage authentication, command authorization, TLS, and persistent configuration are not confirmed in the repository.
CAN initialization caveatThe troubleshooting note states that CAN initialization may block if the CAN peripheral is not properly initialized, and mentions MX_CAN_Init() being commented out in Int_CAN.c.
License clarityGitee indicates that the repository does not specify a license.

Application Value

This project has value as a compact reference for an Ethernet-to-fieldbus motor control gateway. It demonstrates how a low-resource STM32F103 can receive MQTT commands through W5500 Ethernet and dispatch motor control data to either Modbus/RS485 or CAN. The implementation is especially relevant for remote motor control panels, small industrial automation nodes, lab-scale motion control, and gateway prototypes that require deterministic wired Ethernet without adding a full software TCP/IP stack.

Its practical value is strongest as firmware-level reference material. For production deployment, the missing or unconfirmed areas would need additional work: configuration storage, input validation, error handling, security, broker reconnection policy, device management, and field diagnostics.


Final Summary

stm32-gateway is an STM32F103-based industrial gateway firmware that links MQTT over W5500 Ethernet with CAN and RS485/Modbus motor control. The strongest technical point is the separation of cloud/network-side command reception from fieldbus-side control through FreeRTOS tasks and queues. The W5500 functions as the Ethernet TCP/IP communication component, and the implementation uses WIZnet hardware socket behavior, so TOE usage is confirmed. Hybrid wired/wireless networking is not confirmed.


Author Information

ItemInformation
Repository ownerzxh / zxh34
Repository nameSTM32网关 / stm32-gateway
PlatformGitee
Initial commit shown2026-04-25 22:08 +08:00
License저장소 내 명시 없음

The Gitee page lists the owner as zxh, the repository path as zxh34/stm32-gateway, and shows a single initial commit authored on 2026-04-25.


STM32F103 W5500 기반 MQTT-CAN/RS485 모터 제어 게이트웨이

프로젝트 개요

이 프로젝트는 STM32F103 기반 게이트웨이 펌웨어이다. 저장소 설명에 따르면 W5500 칩으로 네트워크를 구성하고, MQTT 프로토콜로 모터 제어 명령을 구독한 뒤, 해당 명령을 CAN 또는 RS485를 통해 스테퍼 모터 드라이버 보드로 전달해 원격 모터 제어를 수행한다.

저장소는 App, Common, Core, Drivers, FreeRTOS, Interface, MDK-ARM, docs 등으로 구성되어 있으며, 언어 비중은 C가 대부분을 차지한다.


프로젝트 유형

항목내용
프로젝트 유형임베디드 산업용 게이트웨이 펌웨어
MCUSTM32F103C8T6 / STM32F103C(8-B)Tx
네트워크 인터페이스SPI 기반 W5500 Ethernet Controller
네트워크 프로토콜MQTT over TCP
하위 장치 인터페이스CAN, RS485/Modbus
RTOSFreeRTOS
주요 기능원격 모터 명령 수신, 프로토콜 선택, 필드버스 명령 전달, 상태 보고

STM32CubeMX 설정 파일인 my_gateway.ioc에는 MCU가 STM32F103C8T6로 설정되어 있고, CAN, SPI2, USART1, USART2가 활성화되어 있다. 또한 W5500용 CSRST GPIO 라벨이 확인된다.


시스템 구조

 
MQTT Broker / Host PC
        |
        | Ethernet TCP/MQTT
        |
W5500 Ethernet Controller
        |
        | SPI2
        |
STM32F103 Gateway Firmware
        |
        +-- MQTT Task
        |     - W5500 초기화
        |     - MQTT 서버 연결
        |     - gateway_pull 구독
        |     - gateway_push 발행
        |
        +-- Command Parser Task
        |     - JSON 파싱
        |     - connection_type 판별
        |     - device_id / motor_start / motor_dir / motor_round 추출
        |
        +-- Modbus Task
        |     - RS485/Modbus 기반 모터 제어
        |     - coil/register 쓰기
        |     - 속도 읽기 및 MQTT 보고
        |
        +-- CAN Task
              - CAN 프레임 송신
              - CAN 응답 MQTT 전달
 

애플리케이션은 MQTT, CmdParse, Modbus, CAN 네 개의 FreeRTOS 태스크를 생성한다. 또한 MQTT 수신, MQTT 발행, Modbus 명령, CAN 명령을 위한 큐를 각각 생성한다.


동작 흐름

  1. MQTT 태스크가 W5500 네트워크 인터페이스를 초기화하고, MQTT 서버에 연결한 뒤 gateway_pull 토픽을 구독한다. 응답은 gateway_push 토픽으로 발행한다. 
  2. MQTT로 수신된 payload는 xQueue_MQTT_Rx를 통해 명령 파서 태스크로 전달된다. 
  3. 명령 파서는 JSON에서 connection_type, device_id, motor_start, motor_dir, motor_round 필드를 추출한다. 
  4. connection_typers485이면 Modbus 명령 큐로, can이면 CAN 명령 큐로 전달된다. 
  5. Modbus 태스크는 모터 시작/방향 값을 coil로 쓰고, 회전 수를 holding register로 기록한 뒤, input register에서 속도를 읽어 MQTT로 보고한다. 
  6. CAN 태스크는 명령을 CAN 데이터 프레임으로 패킹하고, device_id를 표준 프레임 ID로 사용해 전송한다. 이후 하위 장치 응답을 수신하면 MQTT 발행 큐로 전달한다. 

WIZnet 제품 사용 여부와 시스템 내 역할

항목판단
WIZnet 제품W5500 Ethernet Controller
MCU 연결 방식SPI2
시스템 내 역할MQTT 통신을 위한 Ethernet TCP/IP 경로
드라이버 계층WIZnet ioLibrary 계열 W5500 드라이버 및 socket API
애플리케이션 역할MQTT broker 연결, 명령 구독, 응답 발행

Interface/Ethernet에는 W5500/w5500.c, W5500/w5500.h, socket.c, socket.h, wizchip_conf.c, wizchip_conf.h가 포함되어 있다. 이는 W5500 기반 Ethernet 통신 계층이 저장소 안에 포함되어 있음을 보여준다.

Int_MQTT.c는 Ethernet 초기화 후 socket 기반 네트워크 객체를 생성하고, MQTT 서버의 1883 포트에 연결한 뒤 MQTT client를 초기화하고 gateway_pull을 구독한다.

w5500.c는 파일 설명에서 W5500 HAL Interface로 명시되어 있으며, WIZnet ioLibrary Driver 이력을 포함한다. 또한 SPI를 통한 WIZCHIP_READ, WIZCHIP_WRITE 동작이 구현되어 있어 W5500을 SPI 레지스터 접근 방식으로 제어하는 구조임을 확인할 수 있다.


TOE 사용 여부

TOE 사용 여부: 사용함.

이 프로젝트는 lwIP 같은 MCU 소프트웨어 TCP/IP 스택을 사용하는 구조가 아니라, W5500의 hardware socket 기능을 WIZnet 계열 socket API로 사용하는 구조이다. Int_MQTT.c는 MQTT 초기화 과정에서 “socket programming”을 사용한다고 주석으로 설명하며, NewNetwork()ConnectNetwork()를 통해 MQTT 서버에 TCP 연결을 수행한다.

socket.c에서는 Sn_MR_TCP, Sn_CR_CONNECT, Sn_CR_SEND, Sn_CR_RECV 등 WIZnet socket register와 command 제어가 확인된다. 따라서 TCP/IP 처리는 MCU 소프트웨어 스택이 아니라 W5500의 하드웨어 TCP/IP 엔진에 의존하는 구조로 판단된다.


Hybrid Network 여부

Hybrid Network 여부: 해당 없음.

이 프로젝트는 유선 EthernetCAN/RS485 필드버스를 결합한 구조이다. 저장소 내에서 Wi-Fi 또는 다른 무선 네트워크 경로는 확인되지 않는다. 따라서 유선과 무선이 동시에 사용되는 Hybrid Network 시스템으로 분류하지 않는다.

더 정확한 분류는 다음과 같다.

 
Ethernet-to-CAN/RS485 industrial gateway
 

장점

장점설명
게이트웨이 역할이 명확함MQTT 명령을 CAN 또는 RS485/Modbus 제어 메시지로 변환한다.
실용적인 프로토콜 브리지IP 네트워크와 산업용 필드버스를 연결한다.
W5500 기반 EthernetTCP/IP 처리를 W5500 socket 동작에 맡겨 STM32F103의 소프트웨어 스택 부담을 줄인다.
RTOS 기반 역할 분리MQTT, 명령 파싱, Modbus, CAN 처리가 FreeRTOS 태스크와 큐로 분리되어 있다.
디버깅 기록 포함heap, stack, CAN 초기화, 태스크 starvation 관련 FreeRTOS 문제 해결 문서가 포함되어 있다.

docs/freeRTOS_debug_summary.md에는 heap 부족, debug_printf로 인한 stack overflow 위험, CAN 초기화 blocking, MQTT polling 태스크가 낮은 우선순위 태스크를 starvation시키는 문제 등이 정리되어 있다.


한계

한계설명
고정 네트워크 설정IP, gateway, subnet mask, MAC, MQTT server IP가 Int_MQTT.c에 하드코딩되어 있다.
MQTT payload 크기 제약MQTT 송수신 버퍼가 128 bytes로 정의되어 있어 payload 확장성이 제한적이다.
단순한 프로토콜 선택 방식JSON의 connection_type 값이 rs485 또는 can인지 확인해 큐를 나누는 구조이며, 더 복잡한 프로토콜 협상은 확인되지 않는다.
보안 요소 미확인메시지 인증, 명령 권한 검증, TLS, 영구 설정 저장은 저장소 내 명시 없음.
CAN 초기화 주의점문서에는 CAN 외부 설정이 올바르지 않으면 HAL_CAN_Start()에서 blocking될 수 있고, Int_CAN.c 내부의 MX_CAN_Init()이 주석 처리되어 있다는 내용이 기록되어 있다.
라이선스 불명확Gitee 페이지는 이 저장소가 license를 명시하지 않았다고 표시한다.

적용 가치

이 프로젝트는 Ethernet-to-fieldbus 모터 제어 게이트웨이의 소형 구현 예제로 가치가 있다. 저자원 STM32F103 환경에서 W5500 Ethernet으로 MQTT 명령을 수신하고, 이를 Modbus/RS485 또는 CAN 제어 메시지로 분기하는 구조를 확인할 수 있다.

적용 가능성이 높은 영역은 원격 모터 제어 패널, 소형 산업 자동화 노드, 실험실 수준의 모션 제어 시스템, W5500 기반 wired Ethernet 게이트웨이 프로토타입이다.

상용 수준으로 확장하려면 설정 저장, 입력 검증, 예외 처리, 보안, MQTT broker 재연결 정책, 장치 관리, 현장 진단 기능이 추가되어야 한다.


최종 요약

stm32-gateway는 STM32F103 기반의 W5500 Ethernet 게이트웨이 펌웨어이다. MQTT로 수신한 원격 모터 제어 명령을 JSON으로 해석하고, connection_type에 따라 CAN 또는 RS485/Modbus 경로로 전달한다. W5500은 시스템의 Ethernet TCP/IP 통신 구성 요소로 사용되며, socket register 기반 동작이 확인되므로 TOE 사용은 확인된다. 유선 Ethernet과 무선 네트워크가 동시에 사용되는 구조는 확인되지 않으므로 Hybrid Network로 분류하지 않는다.


저자 정보

항목내용
저장소 소유자zxh / zxh34
저장소명STM32网关 / stm32-gateway
플랫폼Gitee
확인된 초기 commit2026-04-25 22:08 +08:00
라이선스저장소 내 명시 없음

Gitee 페이지에는 소유자가 zxh, 저장소 경로가 zxh34/stm32-gateway로 표시되어 있으며, 초기 commit은 2026-04-25에 작성된 것으로 확인된다.

Documents
  • stm32-gateway

Comments Write