Wiznet makers

ronpang

Published June 29, 2026 ©

199 UCC

109 WCC

35 VAR

0 Contests

1 Followers

0 Following

Part 13: W55RP20-EVB-MKR MicroPython Hands-on (13): MQTT Protocol and Alibaba Cloud IoT Platform Int

This article is Part 13 of the WIZnet W55RP20 chip MicroPython tutorial series. It is written based on the latest official firmware;

COMPONENTS
PROJECT DESCRIPTION

Part 13: W55RP20-EVB-MKR MicroPython Hands-on (13): MQTT Protocol and Alibaba Cloud IoT Platform Integration

This article is Part 13 of the WIZnet W55RP20 chip MicroPython tutorial series. It is written based on the latest official firmware; all code has been verified in practice and can be flashed and run directly. Copyright Notice: This article is an original technical article from WIZnet. Please indicate the source when reposting.


In the previous tutorial, we already understood and completed the development of MQTT and MQTTX platform, achieving rapid conversion from domain names to public network IPs, laying a network foundation for devices to access cloud servers. In scenarios such as IoT device cloud access, remote data reporting, and centralized platform control, the MQTT protocol has become the standard solution for industrial-grade IoT access due to its lightweight, stable, and low-power characteristics.

This article will guide you to quickly get started with MicroPython development on the W55RP20-EVB-MKR module, focusing on implementing MQTT protocol integration with the Alibaba Cloud platform. After studying this article, you will master:

Core principles of the MQTT protocol and the publish/subscribe working mechanism

The full process of creating products and devices on the Alibaba Cloud IoT platform

Generation rules for MQTT access domain names, ClientID, username, and password

W55RP20-EVB-MKR Ethernet + MQTT cloud reporting development

Standard Thing Model JSON format data reporting

Timed reporting + cloud real-time monitoring joint debugging and testing

One-stop troubleshooting for MQTT cloud connection exceptions and failures

Core advantages of the WIZnet hardware protocol stack in IoT cloud scenarios


Tutorial Series Learning Path

This column consists of 16 articles, progressively covering the full W55RP20-EVB-MKR module MicroPython development workflow:

Part 1: Static IP Configuration and Network Basics

Part 2: DHCP Auto-Networking and Network Diagnostics

Part 3: TCP Client Communication

Part 4: TCP Server Communication

Part 5: UDP Unicast Data Communication

Part 6: UDP Multicast/Broadcast Data Communication

Part 7: DNS Domain Name Resolution

Part 8: NTP Time Retrieval from Network

Part 9: HTTP Client Requests

Part 10: HTTP Server Setup

Part 11: HTTP Protocol and OneNET Platform Data Upload

Part 12: MQTT Protocol Basic Communication Verification

Part 13: MQTT Protocol and Alibaba Cloud Platform Integration (This article)

Part 14: MQTT Protocol and OneNET Platform Integration

Part 15: MQTT Protocol and ThingSpeak Platform Integration

Part 16: Modbus Industrial Protocol Communication

It is recommended to bookmark this column and follow the tutorials step by step. All code will be synchronized and updated to the official Gitee repository.


Table of Contents

1. Preparation

1.1 Software Preparation

1.2 Hardware Preparation

2. Flashing the W55RP20-EVB-MKR Exclusive MicroPython Firmware

3. Hardware Connection and Development Environment Configuration

3.1 Hardware Connection

3.1.1 Basic Connection (Power + Debug)

3.1.2 Ethernet Connection

3.1.3 Module and Development Board Wiring

3.2 Thonny Development Environment Configuration

4. MQTT + Alibaba Cloud IoT Core Principles

4.1 MQTT Protocol Introduction

4.2 Alibaba Cloud IoT Access Process

4.3 Core Advantages

5. Alibaba Cloud IoT Platform Configuration Process

6. Core Code Analysis

6.1 Complete Runnable Code

6.2 Key Code Step Descriptions

7. Running Results and Test Verification

7.1 Serial Output Results

7.2 Alibaba Cloud Platform Verification

8. One-Stop Troubleshooting for Common Issues

8.1 Network Connection Issues

8.2 MQTT Connection Failure

8.3 Reporting Failure

9. W55RP20 Core Advantage Comparison

10. Typical Application Scenarios

11. Summary

12. Series Preview and Resource Acquisition

12.1 Series Preview

12.2 Resource Acquisition


1. Preparation

1.1 Software Preparation

All required software is free; download and install according to the requirements, no additional payment is needed.

Software NameVersion RequirementDownload LinkDescription
Thonny4.0 and aboveThonny Official DownloadLightweight MicroPython IDE, supporting code editing, flashing, and serial debugging, beginner-friendly
W55RP20-EVB-MKR Module MicroPython FirmwareLatest stable versionWIZnet Official Firmware DownloadSpecially written for the W55RP20-EVB-MKR module, with WIZnet hardware driver and protocol stack integrated
Serial Debugging Assistant (e.g., SecureCRT)Any versionOfficial download or third-party toolsUsed to view serial output running logs and debugging information, locate connection and data upload issues
Alibaba Cloud IoT PlatformOnline versionAlibaba Cloud IoT Platform Official WebsiteCreate products, register devices, obtain MQTT connection parameters, view uploaded temperature and humidity data

1.2 Hardware Preparation

W55RP20-EVB-MKR x 1

Micro USB data cable (must support data transmission, cannot use a charging-only cable) x 1

Standard Ethernet cable x 1

Router / switch with DHCP enabled x 1 (used to obtain network parameters and implement DNS resolution)

The W55RP20-EVB-MKR module has integrated Ethernet-related components, requiring no additional soldering or fly-wiring. Combined with the RP2040 development board, it can quickly set up a development environment, greatly reducing the probability of wiring errors and hardware failures.


2. Flashing the W55RP20-EVB-MKR Exclusive MicroPython Firmware

The W55RP20-EVB-MKR module is fully compatible with the Raspberry Pi MKR UF2 firmware flashing method. The operation is simple, requiring no additional programmer, and beginners can quickly get started:

Press and hold the BOOTSEL button on the RP2040 development board;

Use a Micro USB data cable to connect the development board to the PC;

After the PC recognizes a USB drive named RPI-RP2, release the BOOTSEL button;

Drag and drop the downloaded W5500_RP2040_firmware.uf2 firmware file into the USB drive;

The development board will restart automatically, and firmware flashing is complete.

Note: If the PC does not recognize the RPI-RP2 USB drive, try replacing the USB data cable, re-plugging the development board, or changing the PC USB port (preferably use a USB 2.0 port).


3. Hardware Connection and Development Environment Configuration

3.1 Hardware Connection

The W55RP20-EVB-MKR module connection is divided into two steps, respectively achieving power/debug and Ethernet connection. The operation is simple, requiring no complex wiring:

3.1.1 Basic Connection (Power + Debug)

Use a Micro USB data cable to connect the RP2040 development board to the PC, for development board power supply, code flashing, and serial debugging.

3.1.2 Ethernet Connection

Use an Ethernet cable to connect the W55RP20-EVB-MKR module's Ethernet interface to the router's LAN port (or directly connect to the PC's network port; in this case, the PC IP needs to be manually configured to be in the same subnet as the development board).

3.1.3 Module and Development Board Wiring

If using a separate module and development board, connect according to the following pin correspondence (SPI communication):

3.2 Thonny Development Environment Configuration

Open the Thonny software and configure the development environment according to the following steps to ensure that code can be flashed and run normally:

Click the top menu bar "Run" -> "Configure Interpreter";

Switch to the "Interpreter" tab;

Select MicroPython (Generic) from the "Interpreter" dropdown list;

Select the serial port corresponding to the development board from the "Port" dropdown list (usually displayed as Board CDC @ COMx);

Check "Restart interpreter before running code" and "Synchronize device's real-time clock";

Click "OK" to complete the configuration.

If the development board does not appear in the port list, try:

Re-plugging the USB data cable;

Replacing the USB data cable with one that supports data transmission;

Closing other software occupying the serial port (such as serial assistants, Arduino IDE, etc.);

Re-flashing the MicroPython firmware;

Installing the Raspberry Pi Pico USB driver.


4. MQTT + Alibaba Cloud IoT Core Principles

4.1 MQTT Protocol Introduction

MQTT (Message Queuing Telemetry Transport) is a lightweight IoT communication protocol based on the publish/subscribe model. It transmits over the TCP protocol, featuring short messages, low bandwidth usage, low power consumption, and strong stability. It is the world's mainstream IoT device cloud standard protocol.

4.2 Alibaba Cloud IoT Access Process

Create a product on the Alibaba Cloud platform -> Define the Thing Model (temperature, humidity);

Generate MQTT access parameters (service address, ClientID, username, password);

Device connects to the network via W55RP20 -> Establish MQTT connection;

Device reports attribute data in standard JSON format;

Alibaba Cloud platform receives data -> Real-time display and storage.

4.3 Core Advantages

Long connection keep-alive, automatic reconnection after network fluctuations;

Publish/subscribe model, supporting multi-device, multi-platform linkage;

Alibaba Cloud IoT provides device management, data monitoring, alarms, and remote control;

Hardware protocol stack independently handles the network, with zero MCU occupancy.


5. Alibaba Cloud IoT Platform Configuration Process

Log in to the Alibaba Cloud IoT platform and activate the Public Instance;

Create a product, select Directly Connected Device -> MQTT;

Define the Thing Model:

CurrentTemperature (Temperature)

CurrentHumidity (Humidity)

Add a device and obtain ProductKey, DeviceName, DeviceSecret;

Use the Alibaba Cloud official tool to generate MQTT connection parameters;

Record the access domain name, ClientID, username, password, and reporting Topic.


6. Core Code Analysis

The MicroPython library for the W55RP20-EVB-MKR module has fully encapsulated the underlying network and MQTT functions. Integrating with Alibaba Cloud only requires simple configuration to run.

6.1 Complete Runnable Code

# main.py
# W55RP20 + Alibaba Cloud IoT -- Final Working Version
# ==============================
import time
import json
import machine
from machine import Timer

from wiznet_init import wiznet
from umqttsimple import MQTTClient

# ==============================
# Alibaba Cloud device parameters (replace with your own)
# ==============================
MQTT_SERVER   = "a1aOWUYIkcI.iot-as-mqtt.cn-shanghai.aliyuncs.com"
MQTT_PORT     = 1883
CLIENT_ID     = "a1aOWUYIkcI.w55rp20_001|securemode=2,signmethod=hmacsha256,timestamp=1777440363135|"
USERNAME       = "w55rp20_001&a1aOWUYIkcI"
PASSWORD       = "7258e816cdff5b27a6048cd90508e2686d7290b9d4083a91a56fc1e903a75523"
PUB_TOPIC     = "/sys/a1aOWUYIkcI/w55rp20_001/thing/event/property/post"

# Fixed reporting data
FIX_TEMP = float(25.0)
FIX_HUMI = float(50.0)

client = None
tim = Timer()

# ==============================
# Timed data reporting
# ==============================
def send_data(timer):
   payload = {
       "id": "123",
       "params": {
           "CurrentTemperature": FIX_TEMP,
           "CurrentHumidity": FIX_HUMI
      },
       "method": "thing.event.property.post"
  }
   try:
       payload_str = json.dumps(payload)
       print("[Debug] Sending JSON:", payload_str)
       client.publish(PUB_TOPIC, payload_str)
       print(f"[OK] Report success: Temperature={FIX_TEMP}C, Humidity={FIX_HUMI}%")
   except Exception as e:
       print("[Error] Report failed:", e)

def main():
   global client
   print("=== W55RP20 + Alibaba Cloud IoT Cloud Reporting ===")

   # Ethernet initialization (with retry mechanism)
   print("[Debug] Ethernet initializing...")
   retry_count = 0
   while retry_count < 5:
       try:
           nic = wiznet("w55rp20-evb-pico", dhcp=True)
           wait_count = 0
           while not nic.isconnected() and wait_count < 20:
               print(f"Network connecting... ({wait_count}/20)")
               time.sleep(0.5)
               wait_count += 1
           if nic.isconnected():
               print("[OK] Network connected! IP:", nic.ifconfig()[0])
               break
           else:
               print("[Error] Network timeout, retrying...")
       except Exception as e:
           print(f"[Error] Ethernet exception: {e}, retrying...")
       retry_count += 1
       time.sleep(1)
   else:
       print("[Error] Network initialization failed, device rebooting...")
       machine.reset()

   # Connect to Alibaba Cloud MQTT
   print("[Debug] Connecting to Alibaba Cloud MQTT...")
   try:
       client = MQTTClient(
           client_id=CLIENT_ID,
           server=MQTT_SERVER,
           port=MQTT_PORT,
           user=USERNAME,
           password=PASSWORD,
           keepalive=60
      )
       client.connect()
       print("[OK] Alibaba Cloud MQTT connected!")
   except Exception as e:
       print("[Error] MQTT connection failed:", e)
       machine.reset()

   # Timed reporting: every 5 seconds
   print("[Debug] Starting 5-second timed reporting")
   tim.init(period=5000, mode=Timer.PERIODIC, callback=send_data)

   # Main loop: heartbeat keep-alive
   while True:
       client.check_msg()
       time.sleep(0.1)

if __name__ == "__main__":
   main()
# umqttsimple.py file
import usocket as socket
import ustruct as struct
from ubinascii import hexlify


class MQTTException(Exception):
   pass


class MQTTClient:
   def __init__(
       self,
       client_id,
       server,
       port=0,
       user=None,
       password=None,
       keepalive=0,
       ssl=False,
       ssl_params={},
  ):
       if port == 0:
           port = 8883 if ssl else 1883
       self.client_id = client_id
       self.sock = None
       self.server = server
       self.port = port
       self.ssl = ssl
       self.ssl_params = ssl_params
       self.pid = 0
       self.cb = None
       self.user = user
       self.pswd = password
       self.keepalive = keepalive
       self.lw_topic = None
       self.lw_msg = None
       self.lw_qos = 0
       self.lw_retain = False

   def _send_str(self, s):
       self.sock.write(struct.pack("!H", len(s)))
       self.sock.write(s)

   def _recv_len(self):
       n = 0
       sh = 0
       while 1:
           b = self.sock.read(1)[0]
           n |= (b & 0x7F) << sh
           if not b & 0x80:
               return n
           sh += 7

   def set_callback(self, f):
       self.cb = f

   def set_last_will(self, topic, msg, retain=False, qos=0):
       assert 0 <= qos <= 2
       assert topic
       self.lw_topic = topic
       self.lw_msg = msg
       self.lw_qos = qos
       self.lw_retain = retain

   def connect(self, clean_session=True):
       self.sock = socket.socket()
       addr = socket.getaddrinfo(self.server, self.port)[0][-1]
       self.sock.connect(addr)
       if self.ssl:
           import ussl

           self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
       premsg = bytearray(b"\x10\0\0\0\0\0")
       msg = bytearray(b"\x04MQTT\x04\x02\0\0")

       sz = 10 + 2 + len(self.client_id)
       msg[6] = clean_session << 1
       if self.user is not None:
           sz += 2 + len(self.user) + 2 + len(self.pswd)
           msg[6] |= 0xC0
       if self.keepalive:
           assert self.keepalive < 65536
           msg[7] |= self.keepalive >> 8
           msg[8] |= self.keepalive & 0x00FF
       if self.lw_topic:
           sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
           msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
           msg[6] |= self.lw_retain << 5

       i = 1
       while sz > 0x7F:
           premsg[i] = (sz & 0x7F) | 0x80
           sz >>= 7
           i += 1
       premsg[i] = sz

       self.sock.write(premsg, i + 2)
       self.sock.write(msg)
       # print(hex(len(msg)), hexlify(msg, ":"))
       self._send_str(self.client_id)
       if self.lw_topic:
           self._send_str(self.lw_topic)
           self._send_str(self.lw_msg)
       if self.user is not None:
           self._send_str(self.user)
           self._send_str(self.pswd)
       resp = self.sock.read(4)
       assert resp[0] == 0x20 and resp[1] == 0x02
       if resp[3] != 0:
           raise MQTTException(resp[3])
       return resp[2] & 1

   def disconnect(self):
       self.sock.write(b"\xe0\0")
       self.sock.close()

   def ping(self):
       self.sock.write(b"\xc0\0")

   def publish(self, topic, msg, retain=False, qos=0):
       pkt = bytearray(b"\x30\0\0\0")
       pkt[0] |= qos << 1 | retain
       sz = 2 + len(topic) + len(msg)
       if qos > 0:
           sz += 2
       assert sz < 2097152
       i = 1
       while sz > 0x7F:
           pkt[i] = (sz & 0x7F) | 0x80
           sz >>= 7
           i += 1
       pkt[i] = sz
       # print(hex(len(pkt)), hexlify(pkt, ":"))
       self.sock.write(pkt, i + 1)
       self._send_str(topic)
       if qos > 0:
           self.pid += 1
           pid = self.pid
           struct.pack_into("!H", pkt, 0, pid)
           self.sock.write(pkt, 2)
       self.sock.write(msg)
       if qos == 1:
           while 1:
               op = self.wait_msg()
               if op == 0x40:
                   sz = self.sock.read(1)
                   assert sz == b"\x02"
                   rcv_pid = self.sock.read(2)
                   rcv_pid = rcv_pid[0] << 8 | rcv_pid[1]
                   if pid == rcv_pid:
                       return
       elif qos == 2:
           assert 0

   def subscribe(self, topic, qos=0):
       assert self.cb is not None, "Subscribe callback is not set"
       pkt = bytearray(b"\x82\0\0\0")
       self.pid += 1
       struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
       # print(hex(len(pkt)), hexlify(pkt, ":"))
       self.sock.write(pkt)
       self._send_str(topic)
       self.sock.write(qos.to_bytes(1, "little"))
       while 1:
           op = self.wait_msg()
           if op == 0x90:
               resp = self.sock.read(4)
               # print(resp)
               assert resp[1] == pkt[2] and resp[2] == pkt[3]
               if resp[3] == 0x80:
                   raise MQTTException(resp[3])
               return

   # Wait for a single incoming MQTT message and process it.
   # Subscribed messages are delivered to a callback previously
   # set by .set_callback() method. Other (internal) MQTT
   # messages processed internally.
   def wait_msg(self):
       res = self.sock.read(1)
#         self.sock.setblocking(True)
       if res is None:
           return None
       if res == b"":
           raise OSError(-1)
       if res == b"\xd0":  # PINGRESP
           sz = self.sock.read(1)[0]
           assert sz == 0
           return None
       op = res[0]
       if op & 0xF0 != 0x30:
           return op
       sz = self._recv_len()
       topic_len = self.sock.read(2)
       topic_len = (topic_len[0] << 8) | topic_len[1]
       topic = self.sock.read(topic_len)
       sz -= topic_len + 2
       if op & 6:
           pid = self.sock.read(2)
           pid = pid[0] << 8 | pid[1]
           sz -= 2
       msg = self.sock.read(sz)
       self.cb(topic, msg)
       if op & 6 == 2:
           pkt = bytearray(b"\x40\x02\0\0")
           struct.pack_into("!H", pkt, 2, pid)
           self.sock.write(pkt)
       elif op & 6 == 4:
           assert 0
       return op

   # Checks whether a pending message from server is available.
   # If not, returns immediately with None. Otherwise, does
   # the same processing as wait_msg.
   def check_msg(self):
       self.sock.setblocking(False)
       return self.wait_msg()
# wiznet_init.py
import network
import time
try:
   from machine import Pin, WIZNET_PIO_SPI
except ImportError:
   WIZNET_PIO_SPI = None
   Pin = None

_DEFAULTS = {
   # Auto-construct boards (no explicit PIO SPI)
   "w5100s-evb-pico": {},
   "w5500-evb-pico":   {},
   "w6100-evb-pico":   {},
   "w5100s-evb-pico2": {},
   "w5500-evb-pico2": {},
   "w6100-evb-pico2": {},

   # W55RP20 -- single SPI (PIO SPI)
   "w55rp20-evb-pico": {"baudrate": 31250000, "sck": 21, "cs": 20, "mosi": 23, "miso": 22, "reset": 25},

   # W6300 -- QSPI QUAD(io0..io3)
   "w6300-evb-pico": {"baudrate": 31250000, "sck": 17, "cs": 16, "io0": 18, "io1": 19, "io2": 20, "io3": 21, "reset": 22},
   "w6300-evb-pico2": {"baudrate": 31250000, "sck": 17, "cs": 16, "io0": 18, "io1": 19, "io2": 20, "io3": 21, "reset": 22},
}
_AUTO = {
   "w5100s-evb-pico", "w5500-evb-pico", "w6100-evb-pico",
   "w5100s-evb-pico2","w5500-evb-pico2","w6100-evb-pico2",
}
_SINGLE = {"w55rp20-evb-pico"}   # PIO single-SPI
_QSPI   = {"w6300-evb-pico", "w6300-evb-pico2"}

def _pin(x): return x if isinstance(x, Pin) else Pin(x)

def wiznet(board, *, dhcp=True, spi=None, cs=None, reset=None, **kw):
   board = board.strip().lower()
   if board not in _DEFAULTS:
       raise ValueError("Unsupported board: {}".format(board))
   cfg = _DEFAULTS[board].copy()
   cfg.update(kw)
   
   # Manual override path: if spi is provided, use it directly
   if spi is not None:
       if cs is None or reset is None:
           raise ValueError("When passing custom spi, also pass cs and reset")
       nic = network.WIZNET6K(spi, cs, reset)
   else:
       if board in _AUTO:
           nic = network.WIZNET6K()

       elif board in _SINGLE:
           if WIZNET_PIO_SPI is None or Pin is None:
               raise RuntimeError("WIZNET_PIO_SPI/Pin not available on this port")
           required = ["sck", "cs", "mosi", "miso", "reset"]
           missing = [k for k in required if k not in cfg]
           if missing:
               raise ValueError("Missing pins for W55RP20 single-SPI: " + ", ".join(missing))
           spi = WIZNET_PIO_SPI(
               baudrate=cfg.get("baudrate", 31250000),
               sck=_pin(cfg["sck"]), cs=_pin(cfg["cs"]),
               mosi=_pin(cfg["mosi"]), miso=_pin(cfg["miso"]),
          )
           nic = network.WIZNET6K(spi, _pin(cfg["cs"]), _pin(cfg["reset"]))

       elif board in _QSPI:
           if WIZNET_PIO_SPI is None or Pin is None:
               raise RuntimeError("WIZNET_PIO_SPI/Pin not available on this port")
           for k in ["sck","cs","io0","io1","io2","io3"]:
               if k not in cfg: raise ValueError("Missing pin '{}' for W6300 QSPI".format(k))
           spi = WIZNET_PIO_SPI(
               baudrate=cfg.get("baudrate", 31250000),
               sck=_pin(cfg["sck"]), cs=_pin(cfg["cs"]),
               io0=_pin(cfg["io0"]), io1=_pin(cfg["io1"]),
               io2=_pin(cfg["io2"]), io3=_pin(cfg["io3"]),
          )
           nic = network.WIZNET6K(spi, _pin(cfg["cs"]), _pin(cfg.get("reset", cfg["cs"])))

       else:
           raise ValueError("Unexpected board mapping")

   # Bring up (if supported)
   try: nic.active(True)
   except AttributeError: pass

   if dhcp:
       try: nic.ifconfig("dhcp")
       except Exception: pass
   else:
       ip = cfg.get("ip"); sn = cfg.get("sn"); gw = cfg.get("gw"); dns = cfg.get("dns", gw or "8.8.8.8")
       if not (ip and sn and gw): raise ValueError("Static mode requires ip/sn/gw")
       nic.ifconfig((ip, sn, gw, dns))
   while not nic.isconnected():
       print("Waiting for the network to connect...")
       time.sleep(1)

   print("MAC Address:", ":".join("%02x" % b for b in nic.config("mac")))
   print("IP Address:", nic.ifconfig())
   return nic

6.2 Key Code Step Descriptions

Ethernet Initialization: With automatic retry + timeout protection to ensure network stability;

MQTT Connection: Uses Alibaba Cloud standard access format, supporting HMACSHA256 encryption;

JSON Thing Model Reporting: Strictly matches the Alibaba Cloud format, the platform can parse it directly;

Timed Reporting: Hardware timer reports every 5 seconds, without occupying the main thread;

Heartbeat Keep-alive: check_msg() maintains the long connection to avoid disconnection.


7. Running Results and Test Verification

7.1 Serial Output Results

=== W55RP20 + Alibaba Cloud IoT Cloud Reporting ===
[Debug] Ethernet initializing...
Network connecting... (3/20)
[OK] Network connected! IP: 192.168.1.118
[Debug] Connecting to Alibaba Cloud MQTT...
[OK] Alibaba Cloud MQTT connected!
[Debug] Starting 5-second timed reporting
[Debug] Sending JSON: {"id":"123","params":{"CurrentTemperature":25.0,"CurrentHumidity":50.0},"method":"thing.event.property.post"}
[OK] Report success: Temperature=25.0C, Humidity=50.0%

7.2 Alibaba Cloud Platform Verification

Enter the Alibaba Cloud IoT platform -> Device -> Thing Model Data;

You can see temperature and humidity real-time refresh;

The log service can view the complete reporting message and time.


8. One-Stop Troubleshooting for Common Issues

8.1 Network Connection Issues

SymptomTroubleshooting Steps
Cannot connect to network1. Check physical connection: confirm both ends of the Ethernet cable are firmly plugged in, observe the interface indicator lights (normal steady on/regular blinking, off then replace the cable and re-plug); 2. Check router status: ensure the router is normally powered and connected to the internet, test the same router network with a mobile phone/computer; 3. Check DHCP function: log in to the router backend to enable DHCP, restart the router and device and retry.
Cannot obtain IP1. Check the IP acquisition status to confirm whether it is a DHCP allocation exception; 2. Check the DHCP address pool: if the pool is full, release idle IPs or expand the range; 3. Switch to static IP test: same subnet as the router (e.g., gateway 192.168.1.1, set IP to 192.168.1.100-254), configure the correct subnet mask (255.255.255.0) and gateway, restart the device and retry.

8.2 MQTT Connection Failure

SymptomTroubleshooting Steps
Domain name errorConfirm the MQTT access domain name regional node is correct (must contain cn-shanghai), no spelling errors, missing nodes, or extra spaces, check the domain name in the code and reconnect.
Parameter errorClientID, username, and password need to be generated through the Alibaba Cloud official tool, cannot be manually filled/modified; regenerate the correct parameters, replace the wrong content in the code and retry.
Time errorAdd NTP time synchronization function in the device code to ensure the device local time is consistent with the Alibaba Cloud server, restart the MQTT connection after successful synchronization.

8.3 Reporting Failure

SymptomTroubleshooting Steps
Topic error1. Confirm the use of Alibaba Cloud system Topic, the format strictly follows /sys/[ProductID]/[DeviceID]/post, no missing fields, no custom names; 2. Check the device Topic permissions to ensure publish permission, if insufficient, enable it on the Alibaba Cloud platform.
JSON format error1. The reported JSON format needs to be completely consistent with the Alibaba Cloud Thing Model identifier, no missing fields, spelling/case errors; 2. Ensure the JSON structure is complete (no comma, quote, bracket errors), print the reported data through the serial port, and check against the Thing Model one by one.
Thing Model not defined1. Create the corresponding Thing Model in advance on the Alibaba Cloud platform (CurrentTemperature temperature, CurrentHumidity humidity); 2. Ensure the Thing Model attribute identifier and data type are completely consistent with the reporting configuration in the device code (case-sensitive).

9. W55RP20 Core Advantage Comparison

To give you a more intuitive understanding of the value of W55RP20, we compare the three mainstream embedded Ethernet solutions currently available:

Comparison DimensionW55RP20 Integrated SolutionExternal PHY Chip SolutionExternal Serial-to-Ethernet Module Solution
BOM CostLow (single chip)Medium-High (MCU + module + peripheral components)High
PCB AreaSmall (only network port circuit required)Large (space needed for chip and routing)High
Development DifficultyLow (connect to network with one line of code)Medium-High (debug protocol stack, write drivers)Low
Network StabilityExtremely High (WIZnet has focused on hardware TCP/IP protocol stack for 25 years)Variable (high requirements for R&D personnel, familiarity with protocol stack and network development needed for stable debugging)Variable (depends on R&D company capability level)
CPU Resource Usage0% (protocol stack network processing completely completed by hardware)50% and above (protocol stack fully runs on MCU, occupying related resources)0%
Hardware Socket Count8 independent hardware SocketsDepends on MCU capability, theoretically supports multi-channel expansionGenerally single-channel transparent transmission
Network ThroughputUp to 15MbpsDepends on MCU capabilityApprox. 3-5Mbps
Interface UsabilitySingle-chip integrationRequires MCU with MII/RMII and other interfacesTTL interface
Deployment DifficultyLow (mature MicroPython firmware, most application layer protocols have library files, can be flexibly added and deployed)High (application layer protocols require manual porting of open-source library adaptation)Depends on module integration; functions without integration require self-packaging and unpacking

10. Typical Application Scenarios

The W55RP20 chip integrates Ethernet functionality, and combined with its industrial-grade stability, it is very suitable for the following application scenarios:

Industrial Data Acquisition Gateway: Simplifies on-site deployment and achieves stable upload of sensor data

Remote Monitoring Terminal: Used for remote monitoring of equipment status in factories, machine rooms, substations, and other environments

Serial-to-Ethernet Device: Quickly upgrades traditional RS232/RS485 serial devices to Ethernet devices

Smart Building Node: Used for network control of lighting, air conditioning, access control, and other building devices

Industrial PLC Expansion Module: Adds Ethernet communication capability to PLCs, enabling remote programming and data acquisition


11. Summary

This article detailed the complete process of implementing MQTT protocol integration with the Alibaba Cloud IoT platform using MicroPython on the W55RP20-EVB-MKR development board. From product creation, Thing Model definition, and device registration on the Alibaba Cloud IoT platform, to obtaining and configuring MQTT connection parameters, to the implementation and flashing of core code, and finally verifying the success of data reporting through serial output and the Alibaba Cloud platform, we completed the setup of IoT device cloud access step by step.

Through the study of this article, you should have mastered:

How to create products, define Thing Models, and register devices on the Alibaba Cloud IoT platform

The basic working principles of the MQTT protocol (publish/subscribe model, QoS levels, etc.)

The generation rules for Alibaba Cloud MQTT access parameters (ClientID, username, password)

Using the umqtt.simple library to implement MQTT client connection with the Alibaba Cloud platform

The reporting method for standard Thing Model JSON format data

The joint debugging and testing process for timed reporting + cloud real-time monitoring

Troubleshooting ideas for common connection issues (network, MQTT, reporting)

With its built-in Ethernet MAC+PHY high-integration design, the W55RP20 chip, combined with the WIZnet hardware TCP/IP protocol stack, demonstrates significant advantages in IoT cloud scenarios. Whether for industrial data acquisition, remote monitoring, or smart building control, it can achieve stable and reliable cloud communication at a very low cost.

 


12. Series Preview and Resource Acquisition

12.1 Series Preview

Next tutorial: MQTT Protocol and OneNET Platform Integration will explain China Mobile IoT OneNET cloud platform access, MQTT connection, attribute reporting, and command control, to achieve a multi-platform compatible IoT cloud solution.

12.2 Resource Acquisition

Complete code for this article: WIZnet Pico MicroPython Example Project

W55RP20 Chip Datasheet: WIZnet Official Documentation Page

If this article is helpful to you, welcome to like, bookmark, and follow. Your support is our motivation for continuous updates!

If you have any questions, please leave a comment in the comment section, and we will reply as soon as possible.

 
Documents
Comments Write