11. MicroPython development for W5100S/W5500+RP2040<MQTT&Alibaba Cloud Example>
11. MicroPython development for W5100S/W5500+RP2040<MQTT&Alibaba Cloud Example>
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 Alibaba Cloud's IoT platform, and regularly report the temperature and humidity information of the DHT11 sensor and issue instructions from the platform to control the LED lights to turn on and off.
2. Platform operation process
Step One: Create the Product
Step 2: Define the object model
Step 3: Create the device
Step 4: Record parameters
Parameters | Values |
---|---|
mqttHostUrl | iot-06z00dbroeg8dx3.mqtt.iothub.aliyuncs.com |
port | 1883 |
clientId | ieojgBm5q2c.W5100S_W5500|securemode=2,signmethod=hmacsha256,timestamp=1701222846581| |
username | W5100S_W5500&ieojgBm5q2c |
passwd | fdac6b605808aed345f4b98078519b349db65688604c64fc375c12b326e821ff |
Post topic | /sys/ieojgBm5q2c/${deviceName}/thing/event/property/post |
Subscribe topic | /sys/ieojgBm5q2c/${deviceName}/thing/service/property/set |
Note: You need to replace ${deviceName} in the theme of the object model with the device name on the platform
3. WIZnet Ethernet chip
WIZnet mainstream hardware protocol stack Ethernet chip parameter comparison
Model | Embedded Core | Host I/F | TX/RX Buffer | HW Socket | Network Performance |
---|---|---|---|---|---|
W5100S | TCP/IPv4, MAC & PHY | 8bit BUS, SPI | 16KB | 4 | Max 25Mbps |
W6100 | TCP/IPv4/IPv6, MAC & PHY | 8bit BUS, Fast SPI | 32KB | 8 | Max 25Mbps |
W5500 | TCP/IPv4, MAC & PHY | Fast SPI | 32KB | 8 | Max 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
Alibaba Cloud IoT 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_aliyun.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 the Alibaba Cloud MQTT server. If the connection fails, the reset procedure will be entered.
Step 3: Subscribe to the topic, bind the message callback function, and start the timer.
Step 4: Monitor in the main loop whether there is a message, and if so, enter the message callback function for processing. When the timer reaches the set value, the temperature and humidity information is reported to the cloud platform.
Note: You need to change the MQTT parameter definition to the MQTT server parameter of your Alibaba Cloud platform.
from umqttsimple import MQTTClient
from usocket import socket
from machine import Pin,SPI,Timer
import dht
import network
import time
import json
#mqtt config
mqtt_params = {}
mqtt_params['url'] = 'iot-06z00dbroeg8dx3.mqtt.iothub.aliyuncs.com'
mqtt_params['port'] = 1883
mqtt_params['clientid'] = 'ieojgBm5q2c.W5100S_W5500|securemode=2,signmethod=hmacsha256,timestamp=1701222846581|'
mqtt_params['username'] = 'W5100S_W5500&ieojgBm5q2c'
mqtt_params['passwd'] = 'fdac6b605808aed345f4b98078519b349db65688604c64fc375c12b326e821ff'
mqtt_params['pubtopic'] = '/sys/ieojgBm5q2c/W5100S_W5500/thing/event/property/post'
mqtt_params['subtopic'] = '/sys/ieojgBm5q2c/W5100S_W5500/thing/service/property/set'
mqtt_params['pubqos'] = 0
mqtt_params['subqos'] = 0
#LED definitions
led = Pin(25,Pin.OUT)
#Timer-related definitions
message_interval = 5
timer_1s_count = 0
tim = Timer()
#DHT11 definitions
pin = Pin(2,Pin.OUT)
sensor = dht.DHT11(pin)
client = None
"""
W5x00 chip initialization.
param: None
returns: None
"""
def w5x00_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)
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())
"""
Subscribe to the topic message callback function. This function is entered when a message is received from a subscribed topic.
param1: The topic on which the callback is triggered
param2: Message content
returns: None
"""
def sub_cb(topic, msg):
topic = topic.decode('utf-8')
msg = msg.decode('utf-8')
if topic == mqtt_params['subtopic']:
print("\r\ntopic:",topic,"\r\nrecv:", msg)
parsed = json.loads(msg)
if(parsed["params"]["LEDSwitch"] == 1):
print("LED ON!")
led.value(1)
else:
print("LED OFF!")
led.value(0)
sendmsg = '{"id": "123","version": "1.0","params": {"LEDSwitch": %d},"method": "thing.event.property.post"}'%led.value()
client.publish(mqtt_params['pubtopic'],sendmsg,qos = mqtt_params['pubqos'])
print("send:",sendmsg)
"""
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()
sendmsg = '{"id": "123","version": "1.0","params": {"CurrentTemperature": %s,CurrentHumidity:%s},"method": "thing.event.property.post"}'%(str(sensor.temperature()),str(sensor.humidity()))
try:
client.publish(mqtt_params['pubtopic'],sendmsg,qos = mqtt_params['pubqos'])
print("send:",sendmsg)
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()
"""
Subscribe to Topics.
param: None
returns: None
"""
def subscribe():
client.set_callback(sub_cb)
client.subscribe(mqtt_params['subtopic'],mqtt_params['subqos'])
print('subscribed to %s'%mqtt_params['subtopic'])
def main():
global client
print("WIZnet chip MQTT of Aliyun example")
w5x00_init()
try:
client = mqtt_connect()
except OSError as e:
reconnect()
subscribe()
tim.init(freq=1, callback=tick)
while True:
client.wait_msg()
client.disconnect()
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
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.
Step 3: Issue instructions through the platform to control the LED light switch status.
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.