Wiznet makers

ronpang

Published December 04, 2023 ©

125 UCC

10 WCC

32 VAR

0 Contests

1 Followers

0 Following

Original Link

20. W5100S/W5500+RP2040 Raspberry Pi Pico<MQTT connection to Alibaba Cloud to control onboard LED>

20. W5100S/W5500+RP2040 Raspberry Pi Pico<MQTT connection to Alibaba Cloud to control onboard LED>

COMPONENTS Hardware components

WIZnet - W5500-EVB-Pico

x 1


WIZnet - W5100S-EVB-Pico

x 1


PROJECT DESCRIPTION

1 Introduction

The IoT platform provides safe and reliable device connection and communication capabilities, supports device data collection and uploading to the cloud, rule engine data flow, and cloud data delivery to the device. In addition, it also provides convenient and fast device management capabilities, supporting object model definition, structured data storage, and remote debugging, monitoring, and operation and maintenance. This chapter explains how to use the Alibaba Cloud IoT platform and explains how to use devices to connect to the Alibaba Cloud IoT platform.

 Using W5500 + MQTT application protocol in Ethernet applications allows users to more conveniently implement Alibaba Cloud remote connection and communication between devices. This tutorial will introduce the application and precautions of connecting W5500 Ethernet MQTT to Alibaba Cloud to help readers better master this technology.

2. Protocol Introduction

2.1 Preliminary understanding of the steps to create products on Alibaba Cloud IoT Platform

Then let’s get to the point, how to create a product on the Alibaba Cloud public instance platform:

Directly enter the IoT console with an aliyun account. If you have not yet activated the Alibaba Cloud IoT suite service, apply to activate it.

After activation, create a custom product category

Add a test device later

After adding it, click in to view the device and view the connection parameters.

Then go to the product to view the added object model in the function definition.

The following is to view the publication and subscription topics. Replace ${deviceName} with the DeviceName obtained in the previous step and save it.

Set the publishing topic of will messages

2.2 Explanation of Alibaba Cloud object model

The object model is a digital representation of entities in physical space (such as sensors, vehicle-mounted devices, buildings, factories, etc.) in the cloud. From the three dimensions of attributes, services, and events, it describes what the entity is, what it can do, and what it can do to the outside world. What information is provided. Defining these three dimensions of the object model completes the definition of product functions.

Function typeExplanation
PropertyUsed to describe the specific information and status of the device when it is running. For example, the current ambient temperature, smart light switch status, electric fan wind power level, etc. read by environmental monitoring equipment. Properties can be divided into two types: read-write and read-only. Read-write types support reading and setting property values, while read-only types only support reading property values.
ServiceRefers to the instructions or methods that the device can call externally. Input and output parameters can be set in service calls. The input parameters are the parameters when the service is executed, and the output parameters are the results after the service is executed. Compared with attributes, services can implement more complex business logic through a single instruction, such as performing a specific task. Services are divided into two calling methods: asynchronous and synchronous.
EventWhen the device is running, the information actively reported to the cloud generally includes information, alarms and faults that need to be perceived and processed externally. An event can contain multiple output parameters. For example, notification information after a certain task is completed; temperature and time information when equipment fails; operating status when equipment alarms, etc. Events can be subscribed to and pushed.

The IoT platform supports defining multiple sets of capabilities (properties, services, and events) for products. A set of function definitions is a physical model module. Multiple object model modules do not affect each other.

3 WIZnet Ethernet chip

WIZnet mainstream hardware protocol stack Ethernet chip parameter comparison

ModelEmbedded CoreHost I/FTX/RX BufferHW SocketNetwork Performance
W5100STCP/IPv4, MAC & PHY8bit BUS, SPI16KB4Max.25Mbps
W6100TCP/IPv4/IPv6, MAC & PHY8bit BUS, Fast SPI32KB8Max.25Mbps
W5500TCP/IPv4, MAC & PHYFast SPI32KB8Max 15Mbps

W5100S/W6100 supports 8-bit data bus interface, and the network transmission speed will be better than W5500.

W6100 supports IPV6 and is compatible with W5100S hardware. If users who already use W5100S need to support IPv6, they can be Pin to Pin compatible.

W5500 has more Sockets and send and receive buffers than W5100S.

4 Example Overview

4.1 Flowchart

The running block diagram of the program is as follows:

4.2 Core preparation work

Software

Visual Studio Code

WIZnet UartTool

Alibaba Cloud Platform

Hardware

W5100SIO module + RP2040 Raspberry Pi Pico development board or WIZnet W5100S-EVB-Pico development board

Micro USB interface data cable

TTL to USB

cable

4.3 Connection method

Connect the USB port of the PC through the data cable (mainly used for burning programs, but can also be used as a virtual serial port)

Convert TTL serial port to USB and connect the default pin of UART0:

RP2040 GPIO0 (UART0 TX) <----> USB_TTL_RX

RP2040 GPIO1 (UART0 RX) <----> USB_TTL_TX

When wiring using module connection RP2040

RP2040 GPIO16 <----> W5100S MISO

RP2040 GPIO17 <----> W5100S CS

RP2040 GPIO18 <----> W5100S SCK

RP2040 GPIO19 <----> W5100S MOSI

RP2040 GPIO20 <----> W5100S RST

Connect the PC and device to the router LAN port through network cables

4.4 Main code overview

We are using the official ioLibrary_Driver library of WIZnet. The library supports rich protocols and is easy to operate. The chip integrates the TCP/IP protocol stack on the hardware. The library also encapsulates the protocols above the TCP/IP layer. We only need to simply call the corresponding function to complete the application of the protocol. .

Step one: Add the corresponding .h file to the mqtt_aliyun.c file.

Step 2: Define the macros required by DHCP and the macros of the MQTT transceiver cache buff.

Step 3: Define a mqtt connection parameter structure and define it. The value assigned to the structure here is the corresponding connection parameter on Alibaba Cloud, and the settings of the publish and subscribe topics and the will topic are corresponding.

Step 4: Initialize the parameters inside the library.

Step 5: Configuration of network information, initial parameters of mqtt, and flags.

Step 6: Write the timer callback processing function for DHCP and MQTT tick timer processing functions.

Step 7: The main function first initializes the serial port and SPI, and then writes the network configuration parameters of W5100S. After initializing DHCP, it starts DHCP to obtain the IP. When obtained, it prints the obtained IP. When the number of acquisitions exceeds the maximum number of acquisitions, static is used. IP and DNS resolve the domain name, and then initialize MQTT. Then the main loop is a state machine polling. The state machine first enters the connection state. When the connection is successful, the state starts publishing and subscribing, and then subscribes to the will message, and then Alibaba Cloud Send and receive data.

void network_init(wiz_NetInfo *conf_info);
bool repeating_timer_1ms_callback(struct repeating_timer *t);
bool repeating_timer_1s_callback(struct repeating_timer *t);
void mqtt_init(void);
void messageArrived(MessageData *md);
void do_dns(uint8_t *domain_name, uint8_t *remote_ip);
void json_decode(uint8_t *msg);

int main()
{
   /* Variable definition */
   int ret;
   struct repeating_timer timer_1s;
   struct repeating_timer timer_1ms;
   MQTTMessage pubmessage = {0};

   /*mcu init*/
   stdio_init_all();     /*Initialize the serial port*/
   wizchip_initialize(); /*Initialize the SPI*/

   /* LED init */
   gpio_init(LED_PIN);
   gpio_set_dir(LED_PIN, GPIO_OUT);

   /*timer init*/
   add_repeating_timer_ms(1000, repeating_timer_1s_callback, NULL, &timer_1s); // Add DHCP and DNS 1s Tick Timer handler
   add_repeating_timer_ms(1, repeating_timer_1ms_callback, NULL, &timer_1ms);  // Add MQTT 1ms Tick Timer handler

   /*dhcp init*/
   DHCP_init(SOCK_DHCP, ethernet_buf); // DHCP initialization

   /*dns init*/
   DNS_init(SOCK_DNS, ethernet_buf);

   /* Set the network address information */
   printf("wiznet chip mqtt of aliyun example.\r\n");
   network_init(&net_info);              // Configuring Network Information
   print_network_information(&get_info); // Read back the configuration information and print it

   /* Resolve mqtt broker domain names using dns */
   do_dns(mqtt_params.mqttHostUrl, mqtt_params.server_ip);

   /*mqtt init*/
   mqtt_init();

   while (true)
  {
       switch (run_status)
      {
       case CONN:
      {
           ret = MQTTConnect(&c, &data); /* Connect to the MQTT server */
           printf("Connect to the MQTT server: %d.%d.%d.%d:%d\r\n", mqtt_params.server_ip[0], mqtt_params.server_ip[1], mqtt_params.server_ip[2], mqtt_params.server_ip[3], mqtt_params.port);
           printf("Connected:%s\r\n\r\n", ret == SUCCESSS ? "success" : "failed");
           if (ret != SUCCESSS)
          {
               run_status = ERROR;
          }
           else
          {
               run_status = SUB;
          }
           break;
      }
       case SUB:
      {
           ret = MQTTSubscribe(&c, mqtt_params.subtopic, mqtt_params.subQoS, messageArrived); /* Subscribe to Topics */
           printf("Subscribing to %s\r\n", mqtt_params.subtopic);
           printf("Subscribed:%s\r\n\r\n", ret == SUCCESSS ? "success" : "failed");
           if (ret != SUCCESSS)
          {
               run_status = ERROR;
          }
           else
          {
               run_status = PUB_ONLINE;
          }
           run_status = PUB_ONLINE;
           break;
      }
       case PUB_ONLINE:
      {
           pubmessage.qos = 0;
           pubmessage.payload = "W5100S online!";
           pubmessage.payloadlen = strlen(pubmessage.payload);
           ret = MQTTPublish(&c, mqtt_params.willtopic, &pubmessage); /* Publish message */
           if (ret != SUCCESSS)
          {
               run_status = ERROR;
          }
           else
          {
               printf("publish:%s,%s\r\n\r\n", mqtt_params.willtopic, pubmessage.payload);
               run_status = PUB_MESSAGE;
          }
           break;
      }
       case PUB_MESSAGE:
      {
           pubmessage.qos = 0;
           pubmessage.payload = "{\"id\":\"123\",\"version\":\"1.0\",\"params\":{\"CurrentTemperature\":26.6,},\"method\":\"thing.event.property.post\"}";
           pubmessage.payloadlen = strlen(pubmessage.payload);
           ret = MQTTPublish(&c, (uint8_t *)&(mqtt_params.pubtopic), &pubmessage); /* Publish message */
           if (ret != SUCCESSS)
          {
               run_status = ERROR;
          }
           else
          {
               printf("publish:%s,%s\r\n\r\n", mqtt_params.pubtopic, pubmessage.payload);
               run_status = KEEPALIVE;
          }
           break;
      }
       case KEEPALIVE:
      {
           if (MQTTYield(&c, 30) != SUCCESSS) /* keepalive MQTT */
          {
               run_status = ERROR;
          }
           sleep_ms(100);
           break;
      }
       case ERROR: /* Running error */
           printf("system ERROR!");
           sleep_ms(1000);
           break;

       default:
           break;
      }
  }
}

4.5 Results demonstration

1. Open WIZ UartTool, fill in the parameters, obtain the IP, parse the mqtt server domain name, and then connect to Alibaba Cloud. After the connection is successful, the subscribed and published topics will be printed, information will be sent to the server, and simulated object model data will be uploaded. .

2. You can see that the LED light on the board is off. Next, we turn on the light through Alibaba Cloud.

3. You can see that the device has been online, and the object model and data released by the development board have been obtained, and then we see that the LED is off. Enter the online debugging state to set the lights.

 

4. You can see that when Alibaba Cloud completes setting the status of the light, the serial port prints out the received data and parses it through json to turn on the LED light, and then the development board turns on the light. This is the end of the test.

5 Precautions

Do not reverse publishing and subscribing. Otherwise, messages will not be received.

When copying Alibaba Cloud's object model theme, you need to replace {devicename} with the device name.

If we want to use WIZnet's W5500 to implement the example in this chapter, we only need to modify two places:

(1) Find the wizchip_conf.h header file under library/ioLibrary_Driver/Ethernet/ and modify the WIZCHIP macro definition to W5500.

(2) Find the CMakeLists.txt file under library and set COMPILE_SEL to ON. OFF is W5100S and ON is W5500.

Documents
  • Code for this article

  • WIZnet Official Website

  • WIZnet Official IO Library

  • YouTube Demo

Comments Write