Wiznet makers

ronpang

Published January 08, 2024 ©

125 UCC

10 WCC

32 VAR

0 Contests

1 Followers

0 Following

Original Link

12. MicroPython development for W5100S/W5500+RP2040<MQTT&old version OneNET example>

12. MicroPython development for W5100S/W5500+RP2040<MQTT&old version OneNET example>

COMPONENTS Hardware components

WIZnet - W5100S-EVB-Pico

x 1


WIZnet - W5500-EVB-Pico

x 1


PROJECT DESCRIPTION

1 Introduction

In this era of smart hardware and the Internet of Things, MicroPython and Raspberry Pi PICO are leading the new trend of embedded development with their unique advantages. MicroPython, as a streamlined and optimized Python 3 language, provides efficient development and easy debugging for microcontrollers and embedded devices.

 When we combine it with the WIZnet W5100S/W5500 network module, the development potential of MicroPython and Raspberry Pi PICO is further amplified. Both modules have built-in TCP/IP protocol stacks, making it easier to implement network connections on embedded devices. Whether it is data transmission, remote control, or building IoT applications, they provide powerful support.

 In this chapter, we will take WIZnet W5100S as an example, use MicroPython development method to connect to the old version of OneNET MQTT, and regularly report the temperature and humidity information of the DHT11 sensor.

2. Platform operation process

Step One: Create the Product

Step 2: Create the device

Step 3: Create data flow

Step 4: Calculate parameters

ParametersValues
mqttHostUrlmqtt.heclouds.com(Fixed)
port6002(Fixed)
clientId1168615815(Device ID)
username621478(Product ID)
password0123456789(Authentication information)
Post Topic$dp(Fixed)

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

Compared with the software protocol stack, WIZnet's hardware protocol stack Ethernet chip has the following advantages:

Hardware TCP/IP protocol stack: WIZnet's hardware protocol stack chip provides a hardware-implemented TCP/IP protocol stack. This hardware-implemented protocol stack has better performance and stability than software-implemented protocol stacks.

No additional embedded system software stack and memory resources required: Since all Ethernet transmit and receive operations are handled by the independent Ethernet controller, no additional embedded system software stack and memory resources are required.

Resistant to network environment changes and DDoS attacks: Compared with software TCP/IP protocol stacks that are susceptible to network environment changes and DDoS attacks, hardware protocol stack chips can provide more stable Ethernet performance.

Suitable for low-specification embedded systems: Even in low-specification embedded systems, hardware protocol stack chips using WIZnet can show more efficient Internet application operating performance than high-specification systems using software TCP/IP protocol stacks.

4. Example explanation and usage

4.1 Program flow chart

4.2 Test preparation

Software: 

Thonny

OneNET cloud platform

Hardware:

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

DHT11 temperature and humidity sensor

Micro USB interface data cable

cable

4.3 Connection method

Connect to PC USB port via data cable

When using W5100S/W5500 IO module to connect to RP2040

RP2040 GPIO 16 <----> W5100S/W5500 MISO

RP2040 GPIO 17 <----> W5100S/W5500 CS

RP2040 GPIO 18 <----> W5100S/W5500 SCK

RP2040 GPIO 19 <----> W5100S/W5500 MOSI

RP2040 GPIO 20 <----> W5100S/W5500 RST

DHT11 connected to RP2040

RP2040 GPIO 2 <----> DHT11 data

RP2040 3V3 <----> DHT11 VCC

RP2040 GND <----> DHT11 GND

Directly connect to the PC network port through a network cable (or: both the PC and the device are connected to the switch or router LAN port through a network cable)

4.4 Related code

We open the mqtt_onenet_old.py file directly.

Step one: You can see that SPI is initialized in the w5x00_init() function. And register the spi-related pins and reset pins into the library. The subsequent step is to activate the network and use DHCP to configure the network address information. When DHCP fails, configure the static network address information. When the configuration is not successful, the information about the network address-related registers will be printed out, which can help us better troubleshoot the problem.

Step 2: Connect to OneNET's MQTT server. If the connection fails, the reset procedure will be entered.

Step 3: Start the timer to report temperature and humidity information regularly.

Note: Change the MQTT parameter definition to your OneNET’s MQTT parameter

#import library
from umqttsimple import MQTTClient
from usocket import socket
from machine import Pin,SPI,Timer
import dht
import network
import time

#mqtt config
mqtt_params = {}
mqtt_params['url'] = "mqtt.heclouds.com"
mqtt_params['port'] = 6002
mqtt_params['clientid'] = '1168615815'
mqtt_params['username'] = '621478'
mqtt_params['passwd'] = '0123456789'
mqtt_params['pubtopic'] = '$dp'
mqtt_params['pubqos'] = 0

message_interval = 5
timer_1s_count =  0
tim = Timer()

#DHT11 definitions
pin = Pin(2,Pin.OUT)
sensor = dht.DHT11(pin)

#mqtt client
client = None

"""
W5x00 chip initialization.

param: None
returns: None

"""
def w5x00_init():
   #spi init
   spi=SPI(0,2_000_000, mosi=Pin(19),miso=Pin(16),sck=Pin(18))
   nic = network.WIZNET5K(spi,Pin(17),Pin(20)) #spi,cs,reset pin
   nic.active(True)#network active
   
   
   try:
       #DHCP
       print("\r\nConfiguring DHCP")
       nic.ifconfig('dhcp')
   except:
       #None DHCP
       print("\r\nDHCP fails, use static configuration")
       nic.ifconfig(('192.168.1.20','255.255.255.0','192.168.1.1','8.8.8.8'))#Set static network address information
   
   #Print network address information
   print("IP         :",nic.ifconfig()[0])
   print("Subnet Mask:",nic.ifconfig()[1])
   print("Gateway   :",nic.ifconfig()[2])
   print("DNS       :",nic.ifconfig()[3],"\r\n")
   
   #If there is no network connection, the register address information is printed
   while not nic.isconnected():
       time.sleep(1)
       print(nic.regs())

"""
1-second timer callback function.

param1: class timer
returns: None

"""
def tick(timer):
   global timer_1s_count
   global client
   timer_1s_count += 1
   if timer_1s_count >= message_interval:
       timer_1s_count = 0
       sensor.measure()
       msg = '{"CurrentTemperature":%s,"CurrentHumidity":%s}'%(str(sensor.temperature()),str(sensor.humidity()))
       datalen = len(msg)
       temp = list(msg)
       temp.insert(0,chr(datalen%0x100))
       temp.insert(0,chr(datalen//0x100))
       temp.insert(0,"\x03")
       msg = "".join(temp)
       try:
           client.publish(mqtt_params['pubtopic'],msg,qos = mqtt_params['pubqos'])
           print('send:{"CurrentTemperature":%s,"CurrentHumidity":%s}'%(str(sensor.temperature()),str(sensor.humidity())))
       except:
           print("publish error!please wait reset")
           machine.reset()

"""
Connect to the MQTT server.

param: None
returns: None

"""
def mqtt_connect():
   client = MQTTClient(mqtt_params['clientid'], mqtt_params['url'], mqtt_params['port'],mqtt_params['username'],mqtt_params['passwd'],keepalive=60)
   
   client.connect()
   print('Connected to %s MQTT Broker'%(mqtt_params['url']))
   return client

"""
Connection error handler.

param: None
returns: None

"""
def reconnect():
   print('Failed to connected to Broker. Reconnecting...')
   time.sleep(5)
   machine.reset()

def main():
   global client
   print("WIZnet chip MQTT of OneNET(old version MQTT) example")
   w5x00_init()
   
   try:
       client = mqtt_connect()
   except OSError as e:
       reconnect()
       
   tim.init(freq=1, callback=tick)
   while True:
       time.sleep(1)

if __name__ == "__main__":
   main()

4.5 Burning Verification

To test the Ethernet examples, the development environment must be configured to use a Raspberry Pi Pico.

Required development environment

Thonny

If you must compile MicroPython, you must use a Linux or Unix environment.

Note: Because MicroPython's print function enables stdout buffering, sometimes the content will not be printed out immediately.

Running this script must be supported by the umqttsimple.py library. Please see the MQTT protocol example for how to add the umqttsimple.py library.

Step 1: Copy the program to Thonny, then select the environment as Raspberry Pi Pico, and then run

Step 2: You can see that the temperature and humidity information is reported every 5 seconds and is updated in real time on the platform.

5. Precautions

If you use WIZnet's W5500 to implement the examples in this chapter, you only need to burn the firmware of the W5500 and run the example program.

Documents
  • Code for this article

  • YouTube Demo

Comments Write