116825浏览
查看: 116825|回复: 0

[教程] 如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED

[复制链接]
在本教程中,您将学习如何使用Node-RED(一种物联网 (IoT) 可视化编程工具)通过 Raspberry Pi树莓派作为MQTT代理来控制ESP32板上的LED。MQTT是一种轻量级且简单的消息传递协议,允许设备通过网络相互通信。该项目将需要以下组件:ESP32开发板用于将ESP32 连接到计算机的USB 电缆带有Node-RED的Raspberry Pi树莓派安装有ArduinoIDE和PubSubClient库的计算机

为您的项目制造PCB

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图1


步骤 1:在 Qubitro上创建设备

第一步是在 Qubitro平台上创建设备。设备代表云上的物理设备(树莓派Raspberry Pi)。您需要创建一个设备来获取树莓派Raspberry Pi的MQTT凭据和主题。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图2

要在Qubitro上创建设备,请按照以下步骤操作:

1、登录您的Qubitro 帐户并创建一个新项目

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图3

2.然后进入“设备”页面,选择“MQTT”作为通信协议,然后单击“下一步”。
如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图4

3、输入所有详细信息。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图5

4、复制设备 ID、设备令牌、主机名、端口、发布主题和订阅主题。您稍后将在代码中需要这些值。单击“完成”。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图6

您已在Qubitro上成功创建设备。您可以在“设备”页面上看到您的设备。

第 2 步:使用 Arduino IDE 刷新 ESP32

ESP32 是一款功能强大且多功能的微控制器,可以运行 Arduino 代码。您将使用 Arduino IDE 对 ESP32 进行编程,并使其使用 PubSubClient 库与 MQTT 代理进行通信。

要在Arduino IDE中安装ESP32板,您可以按照本教程中的说明操作或使用以下步骤:

从 Arduino IDE 打开首选项窗口:文件 > 首选项。转到“其他板管理器 URL”字段并输入以下 URL: https: //dl.espressif.com/dl/package_esp32_index.json

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图7

打 Boards Manager(工具 > Board > Boards Manager),搜索ESP32,然后单击“ESP32 by Espressif Systems”的安装按钮。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图8

安装后,从“工具”>“开发板”菜单中选择您的 ESP32 开发板。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图9

从 Sketch > Include Library > Manage Libraries 打开库管理器。搜索 PubSubClient 并单击“PubSubClient by Nick O'Leary”的安装按钮。安装后重新启动 Arduino IDE。

第3步:将LED连接到ESP32

LED是一种简单的器件,当电流流过时就会发光。您将LED连接到ESP32的GPIO引脚之一,并使用MQTT消息控制其状态(打开或关闭)。

就我而言,我将使用ESP32开发板上的板载LED。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图10

第四步:为ESP32编写代码

ESP32的代码将执行以下任务:

连接到您的Wi-Fi 网络连接到树莓派Raspberry Pi上 Qubitro MQTT代理从“输出”接收消息并相应地打开或关闭LED

您可以将以下代码复制并粘贴到您的Arduino IDE中。确保将 <your_ssid>、<your_password>、<your_Qubtro_Credientials> 替换为您自己的值。

代码:
  1. #include <WiFi.h>
  2. #define DEBUG_SW 1
  3. #include <PubSubClient.h>
  4. //Relays for switching appliances
  5. #define Relay1            2
  6. int switch_ON_Flag1_previous_I = 0;
  7. // Update these with values suitable for your network.
  8. const char* ssid = "ELDRADO";
  9. const char* password = "amazon123";
  10. const char* mqtt_server = "broker.qubitro.com"; // Local IP address of Raspberry Pi
  11. const char* username = "";
  12. const char* pass = "";
  13. // Subscribed Topics
  14. #define sub1 "output"
  15. WiFiClient espClient;
  16. PubSubClient client(espClient);
  17. unsigned long lastMsg = 0;
  18. #define MSG_BUFFER_SIZE  (50)
  19. char msg[MSG_BUFFER_SIZE];
  20. int value = 0;
  21. // Connecting to WiFi Router
  22. void setup_wifi()
  23. {
  24.   delay(10);
  25.   // We start by connecting to a WiFi network
  26.   Serial.println();
  27.   Serial.print("Connecting to ");
  28.   Serial.println(ssid);
  29.   WiFi.mode(WIFI_STA);
  30.   WiFi.begin(ssid, password);
  31.   while (WiFi.status() != WL_CONNECTED) {
  32.     delay(500);
  33.     Serial.print(".");
  34.   }
  35.   randomSeed(micros());
  36.   Serial.println("");
  37.   Serial.println("WiFi connected");
  38.   Serial.println("IP address: ");
  39.   Serial.println(WiFi.localIP());
  40. }
  41. void callback(char* topic, byte* payload, unsigned int length)
  42. {
  43.   Serial.print("Message arrived [");
  44.   Serial.print(topic);
  45.   Serial.print("] ");
  46.   if (strstr(topic, sub1))
  47.   {
  48.     for (int i = 0; i < length; i++)
  49.     {
  50.       Serial.print((char)payload[i]);
  51.     }
  52.     Serial.println();
  53.     // Switch on the LED if an 1 was received as first character
  54.     if ((char)payload[0] == 'f')
  55.     {
  56.       digitalWrite(Relay1, LOW);   // Turn the LED on (Note that LOW is the voltage level
  57.       // but actually the LED is on; this is because
  58.       // it is active low on the ESP-01)
  59.     } else {
  60.       digitalWrite(Relay1, HIGH);  // Turn the LED off by making the voltage HIGH
  61.     }
  62.   }
  63.   else
  64.   {
  65.     Serial.println("unsubscribed topic");
  66.   }
  67. }
  68. // Connecting to MQTT broker
  69. void reconnect()
  70. {
  71.   // Loop until we're reconnected
  72.   while (!client.connected()) {
  73.     Serial.print("Attempting MQTT connection...");
  74.     // Create a random client ID
  75.     String clientId = "ESP8266Client-";
  76.     clientId += String(random(0xffff), HEX);
  77.     // Attempt to connect
  78.     if (client.connect(clientId.c_str() , username, pass)) {
  79.       Serial.println("connected");
  80.       // Once connected, publish an announcement...
  81.       client.publish("outTopic", "hello world");
  82.       // ... and resubscribe
  83.       client.subscribe(sub1);
  84.     } else {
  85.       Serial.print("failed, rc=");
  86.       Serial.print(client.state());
  87.       Serial.println(" try again in 5 seconds");
  88.       // Wait 5 seconds before retrying
  89.       delay(5000);
  90.     }
  91.   }
  92. }
  93. void setup()
  94. {
  95.   pinMode(Relay1, OUTPUT);
  96.   Serial.begin(115200);
  97.   setup_wifi();
  98.   client.setServer(mqtt_server, 1883);
  99.   client.setCallback(callback);
  100. }
  101. void loop()
  102. {
  103.   if (!client.connected())
  104.   {
  105.     reconnect();
  106.   }
  107.   client. Loop();
  108. }
复制代码

编写代码后,从“工具”菜单中选择正确的板和端口,然后单击“上传”按钮,将其上传到 ESP32 板。

步骤 5:创建 Node-RED 流

Node-RED流程将执行以下任务:

连接到树莓派Raspberry Pi上的MQTT代理订阅名为“output”的主题将消息“true”或“false”发布到名为“output”的主题创建带有按钮和文本节点的仪表板

您可以通过从面板中拖放节点并用电线连接它们来创建 Node-RED流。您还可以从此链接导入流程或使用下面的 JSON 代码:

代码:
  1. {
  2.         "id": "eb8f9c0d054be30c",
  3.         "type": "tab",
  4.         "label": "Flow 2",
  5.         "disabled": false,
  6.         "info": "",
  7.         "env": []
  8.     },
  9.     {
  10.         "id": "4ce6cd876fd5441f",
  11.         "type": "mqtt out",
  12.         "z": "eb8f9c0d054be30c",
  13.         "name": "",
  14.         "topic": "output",
  15.         "qos": "",
  16.         "retain": "",
  17.         "respTopic": "",
  18.         "contentType": "",
  19.         "userProps": "",
  20.         "correl": "",
  21.         "expiry": "",
  22.         "broker": "6d40b7b21c734b53",
  23.         "x": 870,
  24.         "y": 240,
  25.         "wires": []
  26.     },
  27.     {
  28.         "id": "974a7a8bb6db9bf9",
  29.         "type": "mqtt in",
  30.         "z": "eb8f9c0d054be30c",
  31.         "name": "",
  32.         "topic": "output",
  33.         "qos": "2",
  34.         "datatype": "auto-detect",
  35.         "broker": "6d40b7b21c734b53",
  36.         "nl": false,
  37.         "rap": true,
  38.         "rh": 0,
  39.         "inputs": 0,
  40.         "x": 670,
  41.         "y": 320,
  42.         "wires": [
  43.             [
  44.                 "d0dc7378c7bfb03b",
  45.                 "f1219a2eeabe825f"
  46.             ]
  47.         ]
  48.     },
  49.     {
  50.         "id": "d0dc7378c7bfb03b",
  51.         "type": "debug",
  52.         "z": "eb8f9c0d054be30c",
  53.         "name": "debug 4",
  54.         "active": true,
  55.         "tosidebar": true,
  56.         "console": false,
  57.         "tostatus": false,
  58.         "complete": "payload",
  59.         "targetType": "msg",
  60.         "statusVal": "",
  61.         "statusType": "auto",
  62.         "x": 880,
  63.         "y": 320,
  64.         "wires": []
  65.     },
  66.     {
  67.         "id": "6bd227b280e372b7",
  68.         "type": "ui_switch",
  69.         "z": "eb8f9c0d054be30c",
  70.         "name": "",
  71.         "label": "Light One",
  72.         "tooltip": "",
  73.         "group": "cd687a95.00e108",
  74.         "order": 0,
  75.         "width": 0,
  76.         "height": 0,
  77.         "passthru": true,
  78.         "decouple": "false",
  79.         "topic": "topic",
  80.         "topicType": "msg",
  81.         "style": "",
  82.         "onvalue": "true",
  83.         "onvalueType": "bool",
  84.         "onicon": "",
  85.         "oncolor": "",
  86.         "offvalue": "false",
  87.         "offvalueType": "bool",
  88.         "officon": "",
  89.         "offcolor": "",
  90.         "animate": false,
  91.         "x": 680,
  92.         "y": 240,
  93.         "wires": [
  94.             [
  95.                 "4ce6cd876fd5441f"
  96.             ]
  97.         ]
  98.     },
  99.     {
  100.         "id": "f1219a2eeabe825f",
  101.         "type": "ui_text",
  102.         "z": "eb8f9c0d054be30c",
  103.         "group": "cd687a95.00e108",
  104.         "order": 1,
  105.         "width": "6",
  106.         "height": "2",
  107.         "name": "",
  108.         "label": "Status : ",
  109.         "format": "{{msg.payload}}",
  110.         "layout": "row-center",
  111.         "x": 1060,
  112.         "y": 320,
  113.         "wires": []
  114.     },
  115.     {
  116.         "id": "6d40b7b21c734b53",
  117.         "type": "mqtt-broker",
  118.         "name": "Qubitro Downlink",
  119.         "broker": "broker.qubitro.com",
  120.         "port": "1883",
  121.         "clientid": "",
  122.         "autoConnect": true,
  123.         "usetls": false,
  124.         "protocolVersion": "4",
  125.         "keepalive": "60",
  126.         "cleansession": true,
  127.         "autoUnsubscribe": true,
  128.         "birthTopic": "r43MsJYzcVwZtUXVfZo6XD0Ym7CRegewPQXMt$ho",
  129.         "birthQos": "0",
  130.         "birthPayload": "",
  131.         "birthMsg": {},
  132.         "closeTopic": "",
  133.         "closeQos": "0",
  134.         "closePayload": "",
  135.         "closeMsg": {},
  136.         "willTopic": "",
  137.         "willQos": "0",
  138.         "willPayload": "",
  139.         "willMsg": {},
  140.         "userProps": "",
  141.         "sessionExpiry": ""
  142.     },
  143.     {
  144.         "id": "cd687a95.00e108",
  145.         "type": "ui_group",
  146.         "name": "ESP32 Home Controller",
  147.         "tab": "aa146f4d.b53ca",
  148.         "order": 1,
  149.         "disp": true,
  150.         "width": "6",
  151.         "collapse": false
  152.     },
  153.     {
  154.         "id": "aa146f4d.b53ca",
  155.         "type": "ui_tab",
  156.         "name": "Demo Lab",
  157.         "icon": "dashboard",
  158.         "order": 1,
  159.         "disabled": false,
  160.         "hidden": false
  161.     }
复制代码

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图11

输入开关在打开时将发送“true”,在触发关闭时将发送“false”。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图12

然后单击Qubitro上行链路托盘并编辑属性。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图13

在这里您需要替换您的连接详细信息和凭据。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图14

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图15

接下来,只需部署流程即可。并导航到node-red服务器的/ui。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图16

您可以在此处切换开关以打开和关闭导联。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图17

另外,打开串行监视器并检查节点红色响应。

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图18

结论:

如何使用 Node-RED和Raspberry Pi树莓派MQTT控制ESP32上的LED图19

在本教程中,我们了解了如何使用Node-Red和MQTT服务器控制LED。

本文作者:CETech
原文地址:https://community.dfrobot.com/makelog-313500.html


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail