四、实验过程(实验步骤、记录、数据、分析) 1. 在Easy Iot 上添加两个设备用于topic_0和topic_1 2.连接网络,初始化MQTT参数 (1)选择网络服务,加载MQTT及WIFI选项 (2)连接网络 (3)初始化MQTT参数 3. 发送消息 (1)按下A键,发送消息至Topic0,设置一个提示,当A键被按下后,在屏幕上显示“A已按下” (2)按下B键,发送消息至Topic1,设置一个提示,当B键被按下后,在屏幕上显示“B已按下”。 4. 接受信息 当收到topic_0/topic_1发来的MQTT消息,亮起掌控板上相应的led灯作为提示。 实验代码如下: /*! * MindPlus * mpython * */ #include <MPython.h> #include <DFRobot_Iot.h> // 函数声明 void obloqMqttEventT0(String& message); void obloqMqttEventT1(String& message); // 静态常量 const String topics[5] = {"AH-nIduMR","yfEnSOXMg","","",""}; const MsgHandleCb msgHandles[5] = {obloqMqttEventT0,obloqMqttEventT1,NULL,NULL,NULL}; // 创建对象 DFRobot_Iot myIot; // 主程序开始 void setup() { mPython.begin(); myIot.setMqttCallback(msgHandles); myIot.wifiConnect("602iot", "18wulian"); display.setCursorLine(1); display.printLine("WiFi连接中..."); while (!myIot.wifiStatus()) {yield();} display.fillInLine(1, 0); display.setCursorLine(1); display.printLine("WiFi连接成功!"); myIot.init("iot.dfrobot.com.cn","KvkkSOuGR","","FDkzSOXGRz",topics,1883); myIot.connect(); while (!myIot.connected()) {yield();} display.setCursorLine(2); display.printLine("MQTT连接成功!"); } void loop() { if ((buttonA.isPressed())) { display.fillInLine(3, 0); display.setCursorLine(3); display.printLine("A已按下"); myIot.publish(topic_0, "亮红灯"); } if ((buttonB.isPressed())) { display.fillInLine(3, 0); display.setCursorLine(3); display.printLine("B已按下"); myIot.publish(topic_1, "亮蓝灯"); } } // 事件回调函数 void obloqMqttEventT0(String& message) { display.setCursorLine(4); display.printLine(message); rgb.write(-1, 0xFF0000); } void obloqMqttEventT1(String& message) { display.setCursorLine(4); display.printLine(message); rgb.write(-1, 0x0000FF); } |