{"id":42183,"date":"2017-08-24T10:26:11","date_gmt":"2017-08-24T10:26:11","guid":{"rendered":"http:\/\/randomnerdtutorials.com\/?p=42183"},"modified":"2023-03-21T15:58:53","modified_gmt":"2023-03-21T15:58:53","slug":"esp8266-and-node-red-with-mqtt","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/esp8266-and-node-red-with-mqtt\/","title":{"rendered":"ESP8266 and Node-RED with MQTT (Publish and Subscribe)"},"content":{"rendered":"\n<p>Learn how to publish and subscribe to MQTT topics with the ESP8266 NodeMCU board. In this tutorial, we&#8217;ll use the Node-RED dashboard to control the ESP8266 outputs and display sensor data from the ESP8266 on its interface. The Node-RED software is running on a Raspberry Pi, and the communication between the ESP8266 and the Node-RED software is done via MQTT communication protocol. We&#8217;ll program the ESP8266 using Arduino IDE.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ESP8266_Node-RED_MQTT_Publish_Subscribe.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 and Node-RED with MQTT (Publish and Subscribe)\" class=\"wp-image-129355\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ESP8266_Node-RED_MQTT_Publish_Subscribe.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ESP8266_Node-RED_MQTT_Publish_Subscribe.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ESP8266_Node-RED_MQTT_Publish_Subscribe.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ESP8266_Node-RED_MQTT_Publish_Subscribe.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclgray\"><em>Updated 21 March 2023<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Project Overview<\/h2>\n\n\n\n<p>The following figure shows an overview of what we&#8217;re going to do in this tutorial.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/MQTT-ESP8266-publish-and-subscribe-Node-RED.png?quality=100&#038;strip=all&#038;ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1180\" height=\"654\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/MQTT-ESP8266-publish-and-subscribe-Node-RED.png?resize=1180%2C654&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-42200\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/MQTT-ESP8266-publish-and-subscribe-Node-RED.png?w=1180&amp;quality=100&amp;strip=all&amp;ssl=1 1180w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/MQTT-ESP8266-publish-and-subscribe-Node-RED.png?resize=300%2C166&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/MQTT-ESP8266-publish-and-subscribe-Node-RED.png?resize=768%2C426&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/MQTT-ESP8266-publish-and-subscribe-Node-RED.png?resize=1024%2C568&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/MQTT-ESP8266-publish-and-subscribe-Node-RED.png?resize=750%2C415&amp;quality=100&amp;strip=all&amp;ssl=1 750w\" sizes=\"(max-width: 1180px) 100vw, 1180px\" \/><\/a><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">First, watch the video demonstration below<\/h2>\n\n\n<p style=\"text-align:center\"><iframe width=\"720\" height=\"405\" src=\"https:\/\/www.youtube.com\/embed\/hWERRZJdnSo?rel=0\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Node-RED and Node-RED Dashboard<\/h2>\n\n\n\n<p>To follow this tutorial, you need to have Node-RED and Node-RED Dashboard installed in your <a href=\"https:\/\/makeradvisor.com\/raspberry-pi-board\/\" target=\"_blank\" rel=\"noopener noreferrer\">Raspberry Pi<\/a>. Follow the next tutorials to install and get started with Node-RED and Node-RED dashboard:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-node-red-on-raspberry-pi\/\" target=\"_blank\" rel=\"noopener noreferrer\">Getting started with Node-RED on Raspberry Pi<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-node-red-dashboard\/\">Getting Started with Node-RED Dashboard<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">MQTT Protocol<\/h2>\n\n\n\n<p>In this tutorial, we&#8217;ll establish a communication between a Raspberry Pi running the Node-RED software and an ESP8266 using MQTT.<\/p>\n\n\n\n<p>MQTT stands for&nbsp;<strong>MQ T<\/strong>elemetry&nbsp;<strong>T<\/strong>ransport and it is&nbsp;a nice lightweight publish and subscribe system where you can publish and receive messages as a client.&nbsp;It is a simple messaging protocol, designed for constrained devices and with low bandwidth. So, it\u2019s the perfect solution for Internet of Things applications.<\/p>\n\n\n\n<p>If you want to learn more about MQTT, watch the video below.<\/p>\n\n\n<p style=\"text-align:center\"><iframe width=\"720\" height=\"405\" src=\"https:\/\/www.youtube.com\/embed\/EIxdz-2rhLs?rel=0\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n\n\n\n<p class=\"rntbox rntclblue\">For a written version of this video and additional resources, read this blog post&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/what-is-mqtt-and-how-it-works\/\" target=\"_blank\" rel=\"noopener noreferrer\">What is MQTT and How It Works<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Installing Mosquitto Broker<\/h2>\n\n\n\n<p>The MQTT broker is responsible for&nbsp;receiving&nbsp;all messages,&nbsp;filtering&nbsp;the messages,&nbsp;deciding&nbsp;who is interested in them, and then&nbsp;<strong>publishing<\/strong>&nbsp;the messages to all subscribed clients.<span id=\"more-31713\"><\/span><\/p>\n\n\n\n<p>There are several brokers you can use. In this tutorial, we\u2019re going to use the&nbsp;<strong>Mosquitto Broker<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"200\" height=\"197\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/mosquitto-broker.png?resize=200%2C197&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-73566\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/mosquitto-broker.png?w=200&amp;quality=100&amp;strip=all&amp;ssl=1 200w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/mosquitto-broker.png?resize=80%2C80&amp;quality=100&amp;strip=all&amp;ssl=1 80w\" sizes=\"(max-width: 200px) 100vw, 200px\" \/><\/figure><\/div>\n\n\n<p>You can install the Mosquitto MQTT broker locally on a Raspberry Pi, on your computer, or on the cloud. Follow <strong>one <\/strong>of the next tutorials to install Mosquitto broker:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\" title=\"\">Install Mosquitto MQTT Broker on a Raspberry Pi<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/cloud-mqtt-mosquitto-broker-access-anywhere-digital-ocean\/\" title=\"\">Install Mosquitto MQTT Broker on the Cloud (Digital Ocean)<\/a><\/li>\n<\/ul>\n\n\n\n<p>To see if Mosquitto broker was successfully installed, run the next command:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">pi@raspberry:~ $ <strong>mosquitto -v<\/strong><\/pre>\n\n\n\n<p>This returns the Mosquitto version that is currently running on your Raspberry Pi. It should be 2.0.11 or above.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"621\" height=\"418\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Checking-Mosquitto-Version.png?resize=621%2C418&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Checking Mosquitto Version\" class=\"wp-image-129314\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Checking-Mosquitto-Version.png?w=621&amp;quality=100&amp;strip=all&amp;ssl=1 621w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Checking-Mosquitto-Version.png?resize=300%2C202&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 621px) 100vw, 621px\" \/><\/figure><\/div>\n\n\n<p><strong>Note:<\/strong> the Mosquitto command returns the Mosquitto version that is currently installed, but it also tries to initialize Mosquitto again. Since Mosquitto is already running it prompts an error message. Don&#8217;t worry Mosquitto is properly installed and running if you see a similar message.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Establishing an MQTT communication with Node-RED<\/h2>\n\n\n\n<p>In this section, we\u2019re going to establish an MQTT communication with Node-RED using the MQTT nodes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Dashboard Layout<\/h3>\n\n\n\n<p>The first step is to create the dashboard layout. In this example, we&#8217;ll have a button to control an ESP8266 output, a chart, and a gauge to display temperature and humidity readings from the DHT11 sensor.<\/p>\n\n\n\n<p>On the top right corner, click on the little arrow icon, and click on <strong>Dashboard<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"561\" height=\"301\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Accessing-Node-RED-Dashboard-Layout.jpg?resize=561%2C301&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-129319\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Accessing-Node-RED-Dashboard-Layout.jpg?w=561&amp;quality=100&amp;strip=all&amp;ssl=1 561w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Accessing-Node-RED-Dashboard-Layout.jpg?resize=300%2C161&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 561px) 100vw, 561px\" \/><\/figure><\/div>\n\n\n<p>On the <strong>Layout <\/strong>tab, create a tab called&nbsp;<strong>Room,<\/strong> and inside the Room tab, create two groups:<strong> Lamp<\/strong> and&nbsp;<strong>Sensor<\/strong> as shown in the figure below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"324\" height=\"392\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/node-red-dashboard-layout-example.png?resize=324%2C392&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Node-RED Dashboard layout example\" class=\"wp-image-129320\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/node-red-dashboard-layout-example.png?w=324&amp;quality=100&amp;strip=all&amp;ssl=1 324w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/node-red-dashboard-layout-example.png?resize=248%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 248w\" sizes=\"(max-width: 324px) 100vw, 324px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\">Creating the Flow<\/h3>\n\n\n\n<p>From the dashboard section at the left sidebar, drag a <strong>switch<\/strong>, a <strong>chart, <\/strong>and a <strong>gauge <\/strong>node to the flow. Then drag two <strong>MQTT in<\/strong> and one <strong>MQTT out <\/strong>node to the flow (they are under the network section)\u2014see the figure below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"281\" height=\"162\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/1_NodeRED_flow.png?resize=281%2C162&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-42209\"\/><\/figure><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li><strong>switch<\/strong> &#8211; it will control the ESP8266 output<\/li>\n\n\n\n<li><strong>mqtt output node<\/strong> &#8211; it will publish a message to the ESP8266 accordingly to the switch state<\/li>\n\n\n\n<li><strong>2x<\/strong>&nbsp;<strong>mqtt input nodes<\/strong> &#8211; these nodes will be subscribed to the temperature and humidity topics to receive sensor data from the ESP<\/li>\n\n\n\n<li><strong>chart<\/strong> &#8211; will display the temperature sensor readings<\/li>\n\n\n\n<li><strong>gauge<\/strong> &#8211; will display the humidity sensor readings<\/li>\n<\/ul>\n\n\n\n<p>Node-RED and the MQTT broker need to be connected. To connect the MQTT broker to Node-RED, double-click the<strong> MQTT output<\/strong> node. A new window pops up\u2014as shown in the figure below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"500\" height=\"348\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/MQTT-Output-node.png?resize=500%2C348&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-42210\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/MQTT-Output-node.png?w=500&amp;quality=100&amp;strip=all&amp;ssl=1 500w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/MQTT-Output-node.png?resize=300%2C209&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 500px) 100vw, 500px\" \/><\/figure><\/div>\n\n\n<p><strong>1)<\/strong> Click the <strong>Add new mqtt-broker<\/strong> option.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"656\" height=\"539\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/edit-mqtt-broker-node-red.png?resize=656%2C539&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Edit MQTT broker node node-red\" class=\"wp-image-129321\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/edit-mqtt-broker-node-red.png?w=656&amp;quality=100&amp;strip=all&amp;ssl=1 656w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/edit-mqtt-broker-node-red.png?resize=300%2C246&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 656px) 100vw, 656px\" \/><\/figure><\/div>\n\n\n<p><strong>2) <\/strong>Type <strong>localhost<\/strong> in the <strong>Server<\/strong> field. All the other settings are configured properly by default.<\/p>\n\n\n\n<p>If you&#8217;re not running Node-RED on the same machine that you&#8217;re running Node-RED (Raspberry Pi), insert the MQTT IP address instead of <strong>localhost<\/strong>.<\/p>\n\n\n\n<p><strong>3)<\/strong> Click on the Security tab and insert your MQTT broker username and password if required.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"657\" height=\"360\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/mqtt-broker-password-node-red.png?resize=657%2C360&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-129322\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/mqtt-broker-password-node-red.png?w=657&amp;quality=100&amp;strip=all&amp;ssl=1 657w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/mqtt-broker-password-node-red.png?resize=300%2C164&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 657px) 100vw, 657px\" \/><\/figure><\/div>\n\n\n<p><strong>4)<\/strong> Press <strong>Update <\/strong>and then <strong>Add<\/strong>. The MQTT output node automatically connects to your broker after deploying the Node-RED flow.<\/p>\n\n\n\n<p>Edit all the other nodes&#8217; properties as shown in the following instructions.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Switch Node<\/strong><\/h4>\n\n\n\n<p>The switch sends a <span class=\"rnthl rntliteral\">on<\/span>&nbsp;string message when it&#8217;s on; and sends a <span class=\"rnthl rntliteral\">off<\/span>&nbsp;string message when it&#8217;s off. This node will publish on the&nbsp;<strong>room\/lamp<\/strong> topic. Your ESP8266 will then be subscribed to this topic to receive its messages. Edit the node properties as shown in the picture below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"517\" height=\"716\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/node-red-edit-switch-node-mqtt.png?resize=517%2C716&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-129323\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/node-red-edit-switch-node-mqtt.png?w=517&amp;quality=100&amp;strip=all&amp;ssl=1 517w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/node-red-edit-switch-node-mqtt.png?resize=217%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 217w\" sizes=\"(max-width: 517px) 100vw, 517px\" \/><\/figure><\/div>\n\n\n<h4 class=\"wp-block-heading\">mqtt output node<\/h4>\n\n\n\n<p>This node is connected to the Mosquitto MQTT broker and it will publish in the <strong>room\/lamp<\/strong> topic. Fill in the details as shown below. Insert the topic you want to subscribe to, set the QoS value and if you want to retain the messages or not.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"527\" height=\"426\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT.out-node.png?resize=527%2C426&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MQTT Out node\" class=\"wp-image-129324\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT.out-node.png?w=527&amp;quality=100&amp;strip=all&amp;ssl=1 527w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT.out-node.png?resize=300%2C243&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 527px) 100vw, 527px\" \/><\/figure><\/div>\n\n\n<div class=\"wp-block-group rntbox rntclgray\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<p><strong>What are retained messages in MQTT?<\/strong> <strong>retain (true or false) what does it mean?<\/strong><\/p>\n\n\n\n<p>A retained message is a normal MQTT message with the retained flag set to true. The broker stores the last retained message and the corresponding QoS for that topic.&nbsp;Each client that subscribes to a topic pattern that matches the topic of the retained message receives the retained message immediately after they subscribe. The broker stores only one retained message per topic.<\/p>\n\n\n\n<p><strong>Why is it useful?<\/strong> Retained messages help newly-subscribed clients get a status update immediately after they subscribe to a topic. This is particularly useful to get the status of a device. For example, GPIO 2 is currently HIGH, and the ESP32 suddenly resets. It doesn\u2019t know what the last state of GPIO 2 was. However, if the state is a retained message, it will receive it right after subscribing to the topic and can update the state of GPIO 2 immediately.<\/p>\n<\/div><\/div>\n\n\n\n<h4 class=\"wp-block-heading\">mqtt input node<\/h4>\n\n\n\n<p>This node is subscribed to the <strong>room\/temperature<\/strong> topic to receive temperature sensor data from the ESP8266. The ESP8266 will be publishing the temperature readings on this topic.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"519\" height=\"432\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT-in-node.png?resize=519%2C432&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Node-RED subscribe to temperature topic\" class=\"wp-image-129332\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT-in-node.png?w=519&amp;quality=100&amp;strip=all&amp;ssl=1 519w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT-in-node.png?resize=300%2C250&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 519px) 100vw, 519px\" \/><\/figure><\/div>\n\n\n<h4 class=\"wp-block-heading\">chart node<\/h4>\n\n\n\n<p>The chart will display the readings received on the r<strong>oom\/temperature<\/strong> topic.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"489\" height=\"672\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/chart-node.png?resize=489%2C672&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-42218\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/chart-node.png?w=489&amp;quality=100&amp;strip=all&amp;ssl=1 489w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/chart-node.png?resize=218%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 218w\" sizes=\"(max-width: 489px) 100vw, 489px\" \/><\/figure><\/div>\n\n\n<h4 class=\"wp-block-heading\">mqtt input node<\/h4>\n\n\n\n<p>This node is subscribed to the <strong>room\/humidity<\/strong> topic to receive humidity sensor data from the ESP8266. The ESP8266 will be publishing the humidity readings on this exact topic.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"521\" height=\"456\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT-in-node-humidity.png?resize=521%2C456&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-129336\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT-in-node-humidity.png?w=521&amp;quality=100&amp;strip=all&amp;ssl=1 521w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT-in-node-humidity.png?resize=300%2C263&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 521px) 100vw, 521px\" \/><\/figure><\/div>\n\n\n<h4 class=\"wp-block-heading\">gauge node<\/h4>\n\n\n\n<p>The gauge will display the readings received on the <strong>room\/humidity<\/strong> topic. Edit the gauge properties as shown below. You can adjust the colour gradient to your liking.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"516\" height=\"684\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/edit-gauge-node-humidity-node-red_f.png?resize=516%2C684&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-129342\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/edit-gauge-node-humidity-node-red_f.png?w=516&amp;quality=100&amp;strip=all&amp;ssl=1 516w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/edit-gauge-node-humidity-node-red_f.png?resize=226%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 226w\" sizes=\"(max-width: 516px) 100vw, 516px\" \/><\/figure><\/div>\n\n\n<p>Wire your nodes as shown in the figure below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"344\" height=\"230\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/wiring-nodes.png?resize=344%2C230&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-42220\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/wiring-nodes.png?w=344&amp;quality=100&amp;strip=all&amp;ssl=1 344w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/wiring-nodes.png?resize=300%2C201&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 344px) 100vw, 344px\" \/><\/figure><\/div>\n\n\n<p>Your Node-RED application is ready. Click the&nbsp;<strong>Deploy<\/strong> button on the top right corner.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"145\" height=\"43\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2016\/08\/7-Deploy-Your-Application.png?resize=145%2C43&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-25770\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2016\/08\/7-Deploy-Your-Application.png?w=145&amp;quality=100&amp;strip=all&amp;ssl=1 145w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2016\/08\/7-Deploy-Your-Application.png?resize=80%2C24&amp;quality=100&amp;strip=all&amp;ssl=1 80w\" sizes=\"(max-width: 145px) 100vw, 145px\" \/><\/figure><\/div>\n\n\n<p>The Node-RED application is ready. To see how your dashboard looks go to\u00a0\u00a0<em><strong>http:\/\/<span style=\"color: #ff0000;\">your-pi-ip-address<\/span>:1880\/ui<\/strong><\/em>.<\/p>\n\n\n\n<p>Now, follow the next sections to prepare your ESP8266.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Building the Circuit<\/h2>\n\n\n\n<p>The following sections show you the needed parts and schematics to build the circuit for this project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Parts required<\/h2>\n\n\n\n<p>These are the parts required to build the circuit&nbsp;(click the links below to find the best price at <a href=\"https:\/\/makeradvisor.com\/tools\/\" target=\"_blank\" rel=\"noopener noreferrer\">Maker Advisor<\/a>):<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-board\/\" target=\"_blank\" rel=\"noopener noreferrer\">Raspberry Pi<\/a> \u2013 <a href=\"https:\/\/makeradvisor.com\/best-raspberry-pi-3-starter-kits\/\" target=\"_blank\" rel=\"noopener noreferrer\">read Best Raspberry Pi 3 Starter Kits<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/esp8266-esp-12e-nodemcu-wi-fi-development-board\/\" target=\"_blank\" rel=\"noopener noreferrer\">ESP8266 (ESP-12E nodemcu)<\/a> \u2013 <a href=\"https:\/\/makeradvisor.com\/best-esp8266-wi-fi-development-board\/\" target=\"_blank\" rel=\"noopener noreferrer\">read Best ESP8266 Wi-Fi Development Boards<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/dht11-temperature-humidity-sensor\/\" target=\"_blank\" rel=\"noopener noreferrer\">DHT11 temperature and humidity sensor&nbsp;<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noopener noreferrer\">Breadboard<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener noreferrer\">330&nbsp;\u03a9 resistor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noopener noreferrer\">LED<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noopener noreferrer\">4700&nbsp;\u03a9 resistor<\/a><\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Schematics<\/h2>\n\n\n\n<p>Here are the schematics for this project&#8217;s circuit.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"766\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ESP8266_MQTT_Node-RED_bb-1.png?resize=700%2C766&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-42234\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ESP8266_MQTT_Node-RED_bb-1.png?w=700&amp;quality=100&amp;strip=all&amp;ssl=1 700w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ESP8266_MQTT_Node-RED_bb-1.png?resize=274%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 274w\" sizes=\"(max-width: 700px) 100vw, 700px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Preparing your Arduino IDE<\/h2>\n\n\n\n<p>We&#8217;ll program the ESP8266 using the Arduino IDE. In order to upload code to your ESP8266 using the Arduino IDE, you need to install the ESP8266 add-on (<a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-esp8266-board-arduino-ide\/\" target=\"_blank\" rel=\"noopener noreferrer\">How to Install the ESP8266 Board in Arduino IDE<\/a>). You&#8217;ll also need to install two additional libraries to have everything ready for your ESP8266.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Installing the PubSubClient Library<\/h3>\n\n\n\n<p>The <a href=\"https:\/\/github.com\/knolleary\/pubsubclient\" target=\"_blank\" rel=\"noopener noreferrer\">PubSubClient<\/a> library provides a client for doing simple publish\/subscribe messaging with a server that supports MQTT (basically allows your ESP8266 to talk with Node-RED).<\/p>\n\n\n\n<p><strong>1)<\/strong> <a href=\"https:\/\/github.com\/knolleary\/pubsubclient\/archive\/master.zip\" target=\"_blank\" rel=\"noopener noreferrer\">Click here to download the PubSubClient library<\/a>. You should have a <em>.zip<\/em> folder in your Downloads folder<\/p>\n\n\n\n<p><strong>2)<\/strong> In the Arduino IDE, go to Sketch &gt; Include Library &gt; Add .ZIP library and select the library <em>.zip<\/em> folder you&#8217;ve just downloaded.<\/p>\n\n\n\n<p><strong>3) <\/strong>Restart your Arduino IDE. <\/p>\n\n\n\n<p>The library comes with a number of examples. See File &gt;Examples &gt; PubSubClient within the Arduino IDE software.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Installing the DHT Sensor&nbsp;Library<\/h3>\n\n\n\n<p>To read from the DHT sensor, we\u2019ll use the&nbsp;<a href=\"https:\/\/github.com\/adafruit\/DHT-sensor-library\" target=\"_blank\" rel=\"noreferrer noopener\">DHT library from Adafruit<\/a>. To use this library you also need to install the&nbsp;<a href=\"https:\/\/github.com\/adafruit\/Adafruit_Sensor\" target=\"_blank\" rel=\"noreferrer noopener\">Adafruit Unified Sensor library<\/a>. Follow the next steps to install those libraries.<\/p>\n\n\n\n<p><strong>1)<\/strong> Open your Arduino IDE and go to&nbsp;<strong>Sketch&nbsp;<\/strong>&gt;&nbsp;<strong>Include Library<\/strong>&nbsp;&gt;&nbsp;<strong>Manage Libraries<\/strong>. The Library Manager should open.<\/p>\n\n\n\n<p><strong>2)<\/strong> Search for \u201c<strong>DHT<\/strong>\u201d on the Search box and install the DHT library from Adafruit.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/adafruit_dht_library.png?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Installing Adafruit DHT library\" class=\"wp-image-84293\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/adafruit_dht_library.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/adafruit_dht_library.png?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p><strong>3)<\/strong> After installing the DHT library from Adafruit, type \u201c<strong>Adafruit Unified Sensor<\/strong>\u201d in the search box. Scroll all the way down to find the library and install it.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/adafruit_unified_sensor_library.png?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Installing Adafruit Unified Sensor driver library\" class=\"wp-image-84295\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/adafruit_unified_sensor_library.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/adafruit_unified_sensor_library.png?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p><strong>4)<\/strong> After installing the libraries, restart your Arduino IDE.<\/p>\n\n\n\n<p class=\"rntbox rntclblue\">For more information about the DHT11 sensor and the ESP8266, read&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/esp8266-dht11dht22-temperature-and-humidity-web-server-with-arduino-ide\/\" target=\"_blank\" rel=\"noopener noreferrer\">ESP8266 DHT11\/DHT22 Temperature and Humidity Web Server with Arduino IDE<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Selecting the right board on Arduino IDE<\/h3>\n\n\n\n<p>You also need to select the right board on Arduino IDE:<\/p>\n\n\n\n<p><strong>1)<\/strong> Go to <strong>Tools<\/strong> &gt; <strong>Board <\/strong>and select the ESP8266 board you&#8217;re using.<\/p>\n\n\n\n<p><strong>2)<\/strong> Select the right COM port in <strong>Tools <\/strong>&gt; <strong>Port<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Uploading code<\/h2>\n\n\n\n<p>Now, you can upload the following code to your ESP8266. This code publishes messages with the temperature and humidity from the DHT11 sensor on the <strong>room\/temperature<\/strong> and <strong>room\/humidity<\/strong> topics via MQTT protocol.<\/p>\n\n\n\n<p>The ESP8266 is subscribed to the <strong>room\/lamp<\/strong> topic to receive the messages published on that topic by the Node-RED application, to turn the lamp on or off.<\/p>\n\n\n\n<p>The code is well commented on where you need to make changes. <strong>You need to edit the code with your network credentials (SSID and password), and broker details (Raspberry Pi IP address, mqtt broker username and password.<\/strong><\/p>\n\n\n\n<p>This code is also compatible with other DHT sensors &#8211; you just need to uncomment and comment the right lines of code to choose your sensor.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*****\n \n All the resources for this project:\n http:\/\/randomnerdtutorials.com\/\n \n*****\/\n\n#include &lt;ESP8266WiFi.h&gt;\n#include &lt;PubSubClient.h&gt;\n#include &quot;DHT.h&quot;\n\n\/\/ Uncomment one of the lines bellow for whatever DHT sensor type you're using!\n#define DHTTYPE DHT11   \/\/ DHT 11\n\/\/#define DHTTYPE DHT21   \/\/ DHT 21 (AM2301)\n\/\/#define DHTTYPE DHT22   \/\/ DHT 22  (AM2302), AM2321\n\n\/\/ Change the credentials below, so your ESP8266 connects to your router\nconst char* ssid = &quot;REPLACE_WITH_YOUR_SSID&quot;;\nconst char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;\n\n\/\/ MQTT broker credentials (set to NULL if not required)\nconst char* MQTT_username = &quot;REPLACE_WITH_MQTT_USERNAME&quot;; \nconst char* MQTT_password = &quot;REPLACE_WITH_MQTT_PASSWORD&quot;; \n\n\/\/ Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker\nconst char* mqtt_server = &quot;YOUR_BROKER_IP_ADDRESS&quot;;\n\/\/For example\n\/\/const char* mqtt_server = &quot;192.168.1.106&quot;;\n\n\/\/ Initializes the espClient. You should change the espClient name if you have multiple ESPs running in your home automation system\nWiFiClient espClient;\nPubSubClient client(espClient);\n\n\/\/ DHT Sensor - GPIO 5 = D1 on ESP-12E NodeMCU board\nconst int DHTPin = 5;\n\n\/\/ Lamp - LED - GPIO 4 = D2 on ESP-12E NodeMCU board\nconst int lamp = 4;\n\n\/\/ Initialize DHT sensor.\nDHT dht(DHTPin, DHTTYPE);\n\n\/\/ Timers auxiliar variables\nlong now = millis();\nlong lastMeasure = 0;\n\n\/\/ This functions connects your ESP8266 to your router\nvoid setup_wifi() {\n  delay(10);\n  \/\/ We start by connecting to a WiFi network\n  Serial.println();\n  Serial.print(&quot;Connecting to &quot;);\n  Serial.println(ssid);\n  WiFi.begin(ssid, password);\n  while (WiFi.status() != WL_CONNECTED) {\n    delay(500);\n    Serial.print(&quot;.&quot;);\n  }\n  Serial.println(&quot;&quot;);\n  Serial.print(&quot;WiFi connected - ESP IP address: &quot;);\n  Serial.println(WiFi.localIP());\n}\n\n\/\/ This function is executed when some device publishes a message to a topic that your ESP8266 is subscribed to\n\/\/ Change the function below to add logic to your program, so when a device publishes a message to a topic that \n\/\/ your ESP8266 is subscribed you can actually do something\nvoid callback(String topic, byte* message, unsigned int length) {\n  Serial.print(&quot;Message arrived on topic: &quot;);\n  Serial.print(topic);\n  Serial.print(&quot;. Message: &quot;);\n  String messageTemp;\n  \n  for (int i = 0; i &lt; length; i++) {\n    Serial.print((char)message[i]);\n    messageTemp += (char)message[i];\n  }\n  Serial.println();\n\n  \/\/ Feel free to add more if statements to control more GPIOs with MQTT\n\n  \/\/ If a message is received on the topic room\/lamp, you check if the message is either on or off. Turns the lamp GPIO according to the message\n  if(topic==&quot;room\/lamp&quot;){\n      Serial.print(&quot;Changing Room lamp to &quot;);\n      if(messageTemp == &quot;on&quot;){\n        digitalWrite(lamp, HIGH);\n        Serial.print(&quot;On&quot;);\n      }\n      else if(messageTemp == &quot;off&quot;){\n        digitalWrite(lamp, LOW);\n        Serial.print(&quot;Off&quot;);\n      }\n  }\n  Serial.println();\n}\n\n\/\/ This functions reconnects your ESP8266 to your MQTT broker\n\/\/ Change the function below if you want to subscribe to more topics with your ESP8266 \nvoid reconnect() {\n  \/\/ Loop until we're reconnected\n  while (!client.connected()) {\n    Serial.print(&quot;Attempting MQTT connection...&quot;);\n    \/\/ Attempt to connect\n    \/*\n     YOU MIGHT NEED TO CHANGE THIS LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS\n     To change the ESP device ID, you will have to give a new name to the ESP8266.\n     Here's how it looks:\n       if (client.connect(&quot;ESP8266Client&quot;)) {\n     You can do it like this:\n       if (client.connect(&quot;ESP1_Office&quot;)) {\n     Then, for the other ESP:\n       if (client.connect(&quot;ESP2_Garage&quot;)) {\n      That should solve your MQTT multiple connections problem\n    *\/\n    if (client.connect(&quot;ESP8266Client&quot;, MQTT_username, MQTT_password)) {\n      Serial.println(&quot;connected&quot;);  \n      \/\/ Subscribe or resubscribe to a topic\n      \/\/ You can subscribe to more topics (to control more LEDs in this example)\n      client.subscribe(&quot;room\/lamp&quot;);\n    } else {\n      Serial.print(&quot;failed, rc=&quot;);\n      Serial.print(client.state());\n      Serial.println(&quot; try again in 5 seconds&quot;);\n      \/\/ Wait 5 seconds before retrying\n      delay(5000);\n    }\n  }\n}\n\n\/\/ The setup function sets your ESP GPIOs to Outputs, starts the serial communication at a baud rate of 115200\n\/\/ Sets your mqtt broker and sets the callback function\n\/\/ The callback function is what receives messages and actually controls the LEDs\nvoid setup() {\n  pinMode(lamp, OUTPUT);\n  \n  dht.begin();\n  \n  Serial.begin(115200);\n  setup_wifi();\n  client.setServer(mqtt_server, 1883);\n  client.setCallback(callback);\n\n}\n\n\/\/ For this project, you don't need to change anything in the loop function. Basically it ensures that you ESP is connected to your broker\nvoid loop() {\n\n  if (!client.connected()) {\n    reconnect();\n  }\n  if(!client.loop())\n    client.connect(&quot;ESP8266Client&quot;, MQTT_username, MQTT_password);\n\n  now = millis();\n  \/\/ Publishes new temperature and humidity every 30 seconds\n  if (now - lastMeasure &gt; 30000) {\n    lastMeasure = now;\n    \/\/ Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)\n    float humidity = dht.readHumidity();\n    \/\/ Read temperature as Celsius (the default)\n    float temperatureC = dht.readTemperature();\n    \/\/ Read temperature as Fahrenheit (isFahrenheit = true)\n    float temperatureF = dht.readTemperature(true);\n\n    \/\/ Check if any reads failed and exit early (to try again).\n    if (isnan(humidity) || isnan(temperatureC) || isnan(temperatureF)) {\n      Serial.println(&quot;Failed to read from DHT sensor!&quot;);\n      return;\n    }\n\n    \/\/ Publishes Temperature and Humidity values\n    client.publish(&quot;room\/temperature&quot;, String(temperatureC).c_str());\n    client.publish(&quot;room\/humidity&quot;, String(humidity).c_str());\n    \/\/Uncomment to publish temperature in F degrees\n    \/\/client.publish(&quot;room\/temperature&quot;, String(temperatureF).c_str());\n    \n    Serial.print(&quot;Humidity: &quot;);\n    Serial.print(humidity);\n    Serial.println(&quot; %&quot;);\n    Serial.print(&quot;Temperature: &quot;);\n    Serial.print(temperatureC);\n    Serial.println(&quot; \u00baC&quot;);\n    Serial.print(temperatureF);\n    Serial.println(&quot; \u00baF&quot;);\n  }\n} \n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP8266_NodeRED_MQTT_LED_DHT.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>After uploading the code, and with the Raspberry Pi running your Node-RED application and the Mosquitto broker, you can open the Arduino IDE serial monitor at a baud rate of 115200 and see what&#8217;s happening in real-time.<\/p>\n\n\n\n<p>This is helpful to check if the ESP8266 has established a successful connection to your router and to the Mosquitto broker. You can also see the messages the ESP8266 is receiving and publishing.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"496\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/serial-monitor-arduino-ide.png?resize=750%2C496&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-42232\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/serial-monitor-arduino-ide.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/serial-monitor-arduino-ide.png?resize=300%2C198&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>Congratulations! Your project is now completed.<\/p>\n\n\n\n<p>Go to <em><strong>http:\/\/<span style=\"color: #ff0000;\">your-pi-ip-address<\/span>\/<span style=\"color: #000000;\">ui <\/span><\/strong><\/em>to control the ESP with the &nbsp;Node-RED application. You can access your application in any browser on the same network that your Pi (watch the video demonstration below).<\/p>\n\n\n<p style=\"text-align:center\"><iframe width=\"720\" height=\"405\" src=\"https:\/\/www.youtube.com\/embed\/hWERRZJdnSo?rel=0\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n\n\n\n<p>The application should look something the figure below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"504\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Screenshot_2017-08-21-14-54-45.png?resize=700%2C504&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-42230\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Screenshot_2017-08-21-14-54-45.png?w=700&amp;quality=100&amp;strip=all&amp;ssl=1 700w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/Screenshot_2017-08-21-14-54-45.png?resize=300%2C216&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 700px) 100vw, 700px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Wrapping up<\/h2>\n\n\n\n<p>In this tutorial, we&#8217;ve shown you the basic concepts that will allow you to turn on lights and monitor sensors on your ESP8266 using Node-RED and MQTT communication protocol. You can follow these basic steps to build more advanced projects.<\/p>\n\n\n\n<p>We have other MQTT tutorials using other sensors that you may find useful:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-mqtt-publish-bme280-arduino\/\">ESP8266 NodeMCU MQTT \u2013 Publish <strong>BME280<\/strong> Sensor Readings (Arduino IDE)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-mqtt-publish-ds18b20-arduino\/\">ESP8266 NodeMCU MQTT \u2013 Publish <strong>DS18B20<\/strong> Temperature Readings (Arduino IDE)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-mqtt-publish-bme680-arduino\/\">ESP8266 NodeMCU MQTT \u2013 Publish<strong> BME680<\/strong> Temperature, Humidity, Pressure, and Gas Readings (Arduino IDE)<\/a><\/li>\n<\/ul>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful.<\/p>\n\n\n\n<p>If you like this project and Home Automation make sure you check our eBook: <a href=\"https:\/\/randomnerdtutorials.com\/smart-home-ebook\/\" title=\"\">SMART HOME with Raspberry Pi, ESP32, and ESP8266<\/a>. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to publish and subscribe to MQTT topics with the ESP8266 NodeMCU board. In this tutorial, we&#8217;ll use the Node-RED dashboard to control the ESP8266 outputs and display sensor &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"ESP8266 and Node-RED with MQTT (Publish and Subscribe)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/esp8266-and-node-red-with-mqtt\/#more-42183\" aria-label=\"Read more about ESP8266 and Node-RED with MQTT (Publish and Subscribe)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":1,"featured_media":129355,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[214,265,300,282,283,284,273,264,268,190,192],"tags":[],"class_list":["post-42183","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp8266","category-esp8266-project","category-0-esp8266","category-mqtt","category-mqtt-broker","category-mqtt-client","category-node-red","category-project","category-raspberry-pi-project","category-raspberry-pi","category-r-tutorials"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/08\/ESP8266_Node-RED_MQTT_Publish_Subscribe.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/42183","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=42183"}],"version-history":[{"count":19,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/42183\/revisions"}],"predecessor-version":[{"id":129360,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/42183\/revisions\/129360"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/129355"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=42183"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=42183"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=42183"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}