??在这个智能硬件和物联网时代,MicroPython和树莓派PICO正以其独特的优势引领着嵌入式开发的新潮流。MicroPython作为一种精简优化的Python 3语言,为微控制器和嵌入式设备提供了高效开发和简易调试的
??当我们结合WIZnet W5100S/W5500网络模块,MicroPython和树莓派PICO的开发潜力被进一步放大。这两款模块都内置了TCP/IP协议栈,使得在嵌入式设备上实现网络连接变得更加容易。无论是进行数据传输、远程控制,还是构建物联网应用,它们都提供了强大的支持。
??本章我们将以WIZnet W5100S为例,以MicroPython的开发方式,连接至Thingspeak物联网平台上,并定时上报DHT11传感器的温湿度信息。
第一步:创建通道
第二步:创建设备
参数名 | 参数值 |
---|---|
mqttHostUrl | mqtt3.thingspeak.com(固定) |
port | 1883(固定) |
clientId | Nx45MSAgCAkFNzQYDwwOOAc |
username | Nx45MSAgCAkFNzQYDwwOOAc |
passwd | WGG/tlO7RcEA89G8Ab+vIhmW |
发布主题 | channels/2362531/publish |
注意:发布主题的2362531为Channel ID
注意保存好Password
WIZnet 主流硬件协议栈以太网芯片参数对比
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 |
相较于软件协议栈,WIZnet的硬件协议栈以太网芯片有以下优点:
软件:
硬件:
??我们直接打开mqtt_aliyun.py文件。
第一步:可以看到在w5x00_init()函数中,进行了SPI的初始化。以及将spi相关引脚和复位引脚注册到库中,后续则是激活网络,并使用DHCP配置网络地址信息,当DHCP失败时,则配置静态网络地址信息。当未配置成功时,会打印出网络地址相关寄存器的信息,可以帮助我们更好的排查问题。
第二步:连接阿里云MQTT服务器,连接失败则进入复位程序。
第三步:订阅主题,绑定消息回调函数,开启定时器。
第四步:再主循环中监听是否有消息,如果有则进入消息回调函数进行处理。当定时器达到设定值时上报温湿度信息至云平台。
需注意:要将MQTT参数定义改为您的Thingspeak的MQTT参数
#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'] = 'mqtt3.thingspeak.com'
mqtt_params['port'] = 1883
mqtt_params['clientid'] = 'Nx45MSAgCAkFNzQYDwwOOAc'
mqtt_params['username'] = 'Nx45MSAgCAkFNzQYDwwOOAc'
mqtt_params['passwd'] = 'WGG/tlO7RcEA89G8Ab+vIhmW'
mqtt_params['pubtopic'] = 'channels/2362531/publish'
mqtt_params['pubqos'] = 0
message_interval = 5
timer_1s_count = 0
tim = Timer()
#DHT11 definitions
pin = Pin(2)
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()
sendmsg = "field1={}&field2={}&status=MQTTPUBLISH".format((sensor.temperature()),(sensor.humidity()))
client.publish(mqtt_params['pubtopic'],sendmsg,qos = mqtt_params['pubqos'])
print("send",sendmsg)
"""
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 Thingspeak 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()
要测试以太网示例,必须将开发环境配置为使用Raspberry Pi Pico。
注意:因为MicroPython的print函数是启用了stdout缓冲的,所以有时候并不会第一时间打印出内容。
运行该脚本必须要有umqttsimple.py库支持,如何添加umqttsimple.py库请查看MQTT协议示例
第一步:将程序复制到Thonny中,然后选择环境为Raspberry Pi Pico,再运行
第二步:可以看到此时每间隔5秒上报了一次温湿度信息,并且平台上也会实时更新。
想了解更多,评论留言哦!