{"id":62610,"date":"2018-06-13T12:04:34","date_gmt":"2018-06-13T12:04:34","guid":{"rendered":"http:\/\/randomnerdtutorials.com\/?p=62610"},"modified":"2020-03-25T18:28:44","modified_gmt":"2020-03-25T18:28:44","slug":"esp32-mqtt-publish-subscribe-arduino-ide","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/esp32-mqtt-publish-subscribe-arduino-ide\/","title":{"rendered":"ESP32 MQTT \u2013 Publish and Subscribe with Arduino IDE"},"content":{"rendered":"\n<p>This project shows how to use MQTT communication protocol with the ESP32 to publish messages and subscribe to topics. As an example, we\u2019ll publish BME280 sensor readings to the Node-RED Dashboard, and control an ESP32 output. The ESP32 we\u2019ll be programmed using Arduino IDE.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/featured-image-esp32-mqtt-publish-subscribe.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-62623\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/featured-image-esp32-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\/2018\/05\/featured-image-esp32-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\/2018\/05\/featured-image-esp32-mqtt-publish-subscribe.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/featured-image-esp32-mqtt-publish-subscribe.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Project Overview<\/h2>\n\n\n\n<p>In this example, there&#8217;s a Node-RED application that controls ESP32 outputs and receives sensor readings from the ESP32 using MQTT communication protocol. The Node-RED application is running on a Raspberry Pi.<\/p>\n\n\n\n<p>We&#8217;ll use the <a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\">Mosquitto broker installed<\/a> on the same Raspberry Pi. The broker is responsible for receiving all messages, filtering the messages, decide who is interested in them and publishing the messages to all subscribed clients.<\/p>\n\n\n\n<p>The following figure shows an overview of what we\u2019re going to do in this tutorial.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"800\" height=\"425\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/ESP32-MQTT-bme280.png?resize=800%2C425&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-62628\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/ESP32-MQTT-bme280.png?w=800&amp;quality=100&amp;strip=all&amp;ssl=1 800w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/ESP32-MQTT-bme280.png?resize=300%2C159&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/ESP32-MQTT-bme280.png?resize=768%2C408&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/ESP32-MQTT-bme280.png?resize=280%2C150&amp;quality=100&amp;strip=all&amp;ssl=1 280w\" sizes=\"(max-width: 800px) 100vw, 800px\" \/><\/figure><\/div>\n\n\n\n<ul class=\"wp-block-list\"><li>The Node-RED application publishes messages (&#8220;<strong>on<\/strong>&#8221; or &#8220;<strong>off<\/strong>&#8220;) in the topic <strong>esp32\/output<\/strong>. The ESP32 is subscribed to that topic. So, it receives the message with &#8220;on&#8221; or &#8220;off&#8221; to turn the LED on or off.<\/li><li>The ESP32 publishes temperature on the <strong>esp32\/temperature<\/strong> topic and the humidity on the <strong>esp32\/humidity<\/strong> topic. The Node-RED application is subscribed to those topics. So, it receives temperature and humidity readings that can be displayed on a chart or gauge, for example.<\/li><\/ul>\n\n\n\n<p><strong>Note:<\/strong> there&#8217;s also a similar tutorial on how to use the&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/esp8266-and-node-red-with-mqtt\/\">ESP8266 and Node-RED with MQTT<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>You should be familiar with the Raspberry Pi \u2013&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-raspberry-pi\/\" target=\"_blank\" rel=\"noreferrer noopener\">read Getting Started with Raspberry Pi<\/a>.<\/li><li>You should have the Raspbian operating system installed in your Raspberry Pi \u2013&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/installing-raspbian-lite-enabling-and-connecting-with-ssh\/\">read Installing Raspbian Lite, Enabling and Connecting with SSH<\/a>.<\/li><li>You need&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-node-red-on-raspberry-pi\/\">Node-RED installed on your Pi<\/a>&nbsp;and&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-node-red-dashboard\/\">Node-RED Dashboard<\/a>.<\/li><li>Learn&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/what-is-mqtt-and-how-it-works\/\" target=\"_blank\" rel=\"noreferrer noopener\">what&#8217;s MQTT and how it works<\/a>.<\/li><\/ul>\n\n\n\n<p>If you like home automation and you want to learn more about Node-RED, Raspberry Pi, ESP8266 and Arduino, we recommend trying our course:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/build-a-home-automation-system-for-100\/\" target=\"_blank\" rel=\"noreferrer noopener\">Build a Home Automation System with Node-RED, ESP8266 and Arduino<\/a>. We also have a course dedicated to the ESP32: Enroll in <a href=\"https:\/\/randomnerdtutorials.com\/learn-esp32-with-arduino-ide\/\">Learn ESP32 with Arduino IDE<\/a> course.<\/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=\"noreferrer noopener\">Maker Advisor<\/a>):<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"339\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/parts-required-esp32-bme280-pressure-humidity-temperature.jpg?resize=750%2C339&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-62707\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/parts-required-esp32-bme280-pressure-humidity-temperature.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/parts-required-esp32-bme280-pressure-humidity-temperature.jpg?resize=300%2C136&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-board\/\" target=\"_blank\" rel=\"noreferrer noopener\">Raspberry Pi<\/a> \u2013 <a href=\"https:\/\/makeradvisor.com\/best-raspberry-pi-3-starter-kits\/\" target=\"_blank\" rel=\"noreferrer noopener\">read Best Raspberry Pi 3 Starter Kits<\/a><\/li><li><a href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\" target=\"_blank\" rel=\"noreferrer noopener\">ESP32 DOIT DEVKIT V1 Board<\/a>&nbsp;\u2013 <a href=\"https:\/\/makeradvisor.com\/esp32-development-boards-review-comparison\/\" target=\"_blank\" rel=\"noreferrer noopener\">read ESP32 Development Boards Review and Comparison<\/a><\/li><li><a href=\"https:\/\/makeradvisor.com\/bme280-sensor-module\/\" target=\"_blank\" rel=\"noreferrer noopener\">BME280 sensor module<\/a><\/li><li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\" target=\"_blank\" rel=\"noreferrer noopener\">1x 5mm LED<\/a><\/li><li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noreferrer noopener\">1x 220 Ohm resistor<\/a><\/li><li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noreferrer noopener\">Breadboard<\/a><\/li><li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noreferrer noopener\">Jumper wires<\/a><\/li><\/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\">Introducing the BME280 Sensor Module<\/h2>\n\n\n\n<p>The <a href=\"https:\/\/makeradvisor.com\/bme280-sensor-module\/\" target=\"_blank\" rel=\"noreferrer noopener\">BME280 sensor module<\/a> reads temperature, humidity, and pressure. Because pressure changes with altitude, you can also estimate altitude. However, in this tutorial we&#8217;ll just read temperature and humidity. There are several versions of this sensor module, but we\u2019re using the one shown in the figure below.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"474\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/bme280-temperature-humidity-pressure-esp32.jpg?resize=750%2C474&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-62619\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/bme280-temperature-humidity-pressure-esp32.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/bme280-temperature-humidity-pressure-esp32.jpg?resize=300%2C190&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<p>The sensor can communicate using either SPI or I2C communication protocols (there are modules of this sensor that just communicate with I2C, these just come with four pins).<\/p>\n\n\n\n<p>To use SPI communication protocol, use the following pins:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>SCK \u2013 this is the SPI Clock pin<\/li><li>SDO \u2013 MISO<\/li><li>SDI \u2013 MOSI<\/li><li>CS \u2013 Chip Select<\/li><\/ul>\n\n\n\n<p>To use I2C communication protocol, the sensor uses the following pins:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>SCK \u2013&nbsp;SCL pin<\/li><li>SDI \u2013 SDA pin<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Schematic<\/h2>\n\n\n\n<p>We\u2019re going to use I2C communication with the BME280 sensor module. For that, wire the sensor to the ESP32 SDA and SCL pins, as shown in the following schematic diagram.<\/p>\n\n\n\n<p>We&#8217;ll also control an ESP32 output, an LED connected to GPIO 4.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"460\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/ESP32-bme280-led_bb-1.png?resize=750%2C460&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-62631\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/ESP32-bme280-led_bb-1.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/ESP32-bme280-led_bb-1.png?resize=300%2C184&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<p>Here&#8217;s how your circuit should look:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"600\" height=\"448\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/circuit-breadboard.jpg?resize=600%2C448&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-62624\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/circuit-breadboard.jpg?w=600&amp;quality=100&amp;strip=all&amp;ssl=1 600w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/circuit-breadboard.jpg?resize=300%2C224&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 600px) 100vw, 600px\" \/><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Preparing the Arduino IDE<\/h2>\n\n\n\n<p>There\u2019s an add-on for the Arduino IDE that allows you to program the ESP32 using the Arduino IDE and its programming language. Follow one of the next tutorials to prepare your Arduino IDE to work with the ESP32, if you haven\u2019t already.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/installing-the-esp32-board-in-arduino-ide-windows-instructions\/\"><strong>Windows<\/strong>&nbsp;instructions \u2013 ESP32 Board in Arduino IDE<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/installing-the-esp32-board-in-arduino-ide-mac-and-linux-instructions\/\"><strong>Mac and Linux<\/strong>&nbsp;instructions \u2013 ESP32 Board in Arduino IDE<\/a><\/li><\/ul>\n\n\n\n<p>After making sure you have the ESP32 add-on installed, you can continue with this tutorial.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Installing the PubSubClient Library<\/h4>\n\n\n\n<p>The <a href=\"https:\/\/github.com\/knolleary\/pubsubclient\" target=\"_blank\" rel=\"noreferrer noopener\">PubSubClient<\/a> library provides a client for doing simple publish\/subscribe messaging with a server that supports MQTT (basically allows your ESP32 to talk with Node-RED).<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><a href=\"https:\/\/github.com\/knolleary\/pubsubclient\/archive\/master.zip\" target=\"_blank\" rel=\"noreferrer noopener\">Click here to download the PubSubClient library<\/a>. You should have a <em>.zip<\/em> folder in your Downloads folder<\/li><li>Unzip the <em>.zip<\/em> folder and you should get <strong>pubsubclient-master<\/strong> folder<\/li><li>Rename your folder from&nbsp;<del>pubsubclient-master<\/del> to <strong>pubsubclient<\/strong><\/li><li>Move the <strong>pubsubclient<\/strong> folder to your Arduino IDE installation libraries folder<\/li><li>Then, re-open your Arduino IDE<\/li><\/ol>\n\n\n\n<p>The library comes with a number of example sketches. See <strong>File<\/strong> &gt;<strong>Examples<\/strong> &gt; <strong>PubSubClient<\/strong> within the Arduino IDE software.<\/p>\n\n\n\n<p><strong>Important:&nbsp;<\/strong>PubSubClient is not fully compatible with the ESP32, but the example provided in this tutorial is working very reliably during our tests.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Installing the BME280 library<\/h4>\n\n\n\n<p>To take readings from the BME280 sensor module we&#8217;ll use the <a href=\"https:\/\/github.com\/adafruit\/Adafruit_BME280_Library\" target=\"_blank\" rel=\"noreferrer noopener\">Adafruit_BME280 library<\/a>. Follow the next steps to install the library in your Arduino IDE:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><a href=\"https:\/\/github.com\/adafruit\/Adafruit_BME280_Library\/archive\/master.zip\" target=\"_blank\" rel=\"noreferrer noopener\">Click here to download<\/a> the Adafruit-BME280 library. You should have a .zip folder in your Downloads folder<\/li><li>Unzip the .zip folder and you should get <strong>Adafruit-BME280-Library-master<\/strong> folder<\/li><li>Rename your folder from <del>Adafruit-BME280-Library-master<\/del> to <strong>Adafruit_BME280_Library<\/strong><\/li><li>Move the <strong>Adafruit_BMPE280_Library<\/strong> folder to your Arduino IDE installation libraries folder<\/li><li>Finally, re-open your Arduino IDE<\/li><\/ol>\n\n\n\n<p>Alternatively, you can go to <strong>Sketch<\/strong> &gt; <strong>Include Library<\/strong> &gt; <strong>Manage Libraries<\/strong> and type &#8220;<strong>adafruit bme280<\/strong>&#8221; to search for the library. Then, click install.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Installing the Adafruit_Sensor library<\/h4>\n\n\n\n<p>To use the BME280 library, you also need to install the <a href=\"https:\/\/github.com\/adafruit\/Adafruit_Sensor\" target=\"_blank\" rel=\"noreferrer noopener\">Adafruit_Sensor library<\/a>. Follow the next steps to install the library:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><a href=\"https:\/\/github.com\/adafruit\/Adafruit_Sensor\/archive\/master.zip\" target=\"_blank\" rel=\"noreferrer noopener\">Click here to download<\/a>&nbsp;the Adafruit_Sensor library. You should have a .zip folder in your Downloads folder<\/li><li>Unzip the .zip folder and you should get <strong>Adafruit_Sensor-master<\/strong> folder<\/li><li>Rename your folder from <del>Adafruit_Sensor-master<\/del> to <strong>Adafruit_Sensor<\/strong><\/li><li>Move the <strong>Adafruit_Sensor<\/strong>&nbsp;folder to your Arduino IDE installation libraries folder<\/li><li>Finally, re-open your Arduino IDE<\/li><\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Uploading code<\/h3>\n\n\n\n<p>Now, you can upload the following code to your ESP32. The code is commented on where you need to make changes. <strong>You need to edit the code with your own SSID, password and Raspberry Pi IP address.<\/strong><\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*********\n  Rui Santos\n  Complete project details at https:\/\/randomnerdtutorials.com  \n*********\/\n\n#include &lt;WiFi.h&gt;\n#include &lt;PubSubClient.h&gt;\n#include &lt;Wire.h&gt;\n#include &lt;Adafruit_BME280.h&gt;\n#include &lt;Adafruit_Sensor.h&gt;\n\n\/\/ Replace the next variables with your SSID\/Password combination\nconst char* ssid = &quot;REPLACE_WITH_YOUR_SSID&quot;;\nconst char* password = &quot;REPLACE_WITH_YOUR_PASSWORD&quot;;\n\n\/\/ Add your MQTT Broker IP address, example:\n\/\/const char* mqtt_server = &quot;192.168.1.144&quot;;\nconst char* mqtt_server = &quot;YOUR_MQTT_BROKER_IP_ADDRESS&quot;;\n\nWiFiClient espClient;\nPubSubClient client(espClient);\nlong lastMsg = 0;\nchar msg[50];\nint value = 0;\n\n\/\/uncomment the following lines if you're using SPI\n\/*#include &lt;SPI.h&gt;\n#define BME_SCK 18\n#define BME_MISO 19\n#define BME_MOSI 23\n#define BME_CS 5*\/\n\nAdafruit_BME280 bme; \/\/ I2C\n\/\/Adafruit_BME280 bme(BME_CS); \/\/ hardware SPI\n\/\/Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); \/\/ software SPI\nfloat temperature = 0;\nfloat humidity = 0;\n\n\/\/ LED Pin\nconst int ledPin = 4;\n\nvoid setup() {\n  Serial.begin(115200);\n  \/\/ default settings\n  \/\/ (you can also pass in a Wire library object like &amp;Wire2)\n  \/\/status = bme.begin();  \n  if (!bme.begin(0x76)) {\n    Serial.println(&quot;Could not find a valid BME280 sensor, check wiring!&quot;);\n    while (1);\n  }\n  setup_wifi();\n  client.setServer(mqtt_server, 1883);\n  client.setCallback(callback);\n\n  pinMode(ledPin, OUTPUT);\n}\n\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\n  WiFi.begin(ssid, password);\n\n  while (WiFi.status() != WL_CONNECTED) {\n    delay(500);\n    Serial.print(&quot;.&quot;);\n  }\n\n  Serial.println(&quot;&quot;);\n  Serial.println(&quot;WiFi connected&quot;);\n  Serial.println(&quot;IP address: &quot;);\n  Serial.println(WiFi.localIP());\n}\n\nvoid callback(char* 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 esp32\/output, you check if the message is either &quot;on&quot; or &quot;off&quot;. \n  \/\/ Changes the output state according to the message\n  if (String(topic) == &quot;esp32\/output&quot;) {\n    Serial.print(&quot;Changing output to &quot;);\n    if(messageTemp == &quot;on&quot;){\n      Serial.println(&quot;on&quot;);\n      digitalWrite(ledPin, HIGH);\n    }\n    else if(messageTemp == &quot;off&quot;){\n      Serial.println(&quot;off&quot;);\n      digitalWrite(ledPin, LOW);\n    }\n  }\n}\n\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    if (client.connect(&quot;ESP8266Client&quot;)) {\n      Serial.println(&quot;connected&quot;);\n      \/\/ Subscribe\n      client.subscribe(&quot;esp32\/output&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}\nvoid loop() {\n  if (!client.connected()) {\n    reconnect();\n  }\n  client.loop();\n\n  long now = millis();\n  if (now - lastMsg &gt; 5000) {\n    lastMsg = now;\n    \n    \/\/ Temperature in Celsius\n    temperature = bme.readTemperature();   \n    \/\/ Uncomment the next line to set temperature in Fahrenheit \n    \/\/ (and comment the previous temperature line)\n    \/\/temperature = 1.8 * bme.readTemperature() + 32; \/\/ Temperature in Fahrenheit\n    \n    \/\/ Convert the value to a char array\n    char tempString[8];\n    dtostrf(temperature, 1, 2, tempString);\n    Serial.print(&quot;Temperature: &quot;);\n    Serial.println(tempString);\n    client.publish(&quot;esp32\/temperature&quot;, tempString);\n\n    humidity = bme.readHumidity();\n    \n    \/\/ Convert the value to a char array\n    char humString[8];\n    dtostrf(humidity, 1, 2, humString);\n    Serial.print(&quot;Humidity: &quot;);\n    Serial.println(humString);\n    client.publish(&quot;esp32\/humidity&quot;, humString);\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\/ESP32-MQTT\/ESP32_MQTT_Publish_Subscribe.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>This code publishes temperature and humidity readings on the <strong>esp32\/temperature<\/strong> and <strong>esp32\/humidity<\/strong> topics trough MQTT protocol.<\/p>\n\n\n\n<p>The ESP32 is subscribed to the <strong>esp32\/output&nbsp;<\/strong>topic to receive the messages published on that topic by the Node-RED application. Then, accordingly to the received message, it turns the LED on or off.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Subscribing to MQTT topics<\/h3>\n\n\n\n<p>In the <em>reconnect()<\/em> function, you can subscribe to MQTT topics. In this case, the ESP32 is only subscribed to the<strong> esp32\/output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>client.subscribe(\"esp32\/output\");<\/code><\/pre>\n\n\n\n<p>In the&nbsp;<em>callback()<\/em> function, the ESP32 receives the MQTT messages of the subscribed topics. According to the MQTT topic and message, it turns the LED on or off:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ If a message is received on the topic esp32\/output, you check if the message is either \"on\" or \"off\". \n\/\/ Changes the output state according to the message\nif (String(topic) == \"esp32\/output\") {\n  Serial.print(\"Changing output to \");\n  if (messageTemp == \"on\") {\n    Serial.println(\"on\");\n    digitalWrite(ledPin, HIGH);\n  }\n  else if (messageTemp == \"off\") {\n    Serial.println(\"off\");\n    digitalWrite(ledPin, LOW);\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Publishing MQTT messages<\/h3>\n\n\n\n<p>In the <em>loop(),<\/em> new readings are being published every 5 seconds:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>if (now - lastMsg > 5000) { ... }<\/code><\/pre>\n\n\n\n<p>By default the ESP32 is sending the temperature in Celsius, but you can uncomment the last line to send the temperature in Fahrenheit:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Temperature in Celsius\ntemperature = bme.readTemperature(); \n\/\/ Uncomment the next line to set temperature in Fahrenheit \n\/\/ (and comment the previous temperature line)\n\/\/temperature = 1.8 * bme.readTemperature() + 32; \/\/ Temperature in Fahrenheit<\/code><\/pre>\n\n\n\n<p>You need to convert the temperature float variable to a char array, so that you can publish the temperature reading in the <strong>esp32\/temperature<\/strong> topic:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Convert the value to a char array\nchar tempString&#091;8];\ndtostrf(temperature, 1, 2, tempString);\nSerial.print(\"Temperature: \");\nSerial.println(tempString);\nclient.publish(\"esp32\/temperature\", tempString);<\/code><\/pre>\n\n\n\n<p>The same process is repeated to publish the humidity reading in the <strong>esp32\/humidity<\/strong> topic:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>humidity = bme.readHumidity();\n\/\/ Convert the value to a char array\nchar humString&#091;8];\ndtostrf(humidity, 1, 2, humString);\nSerial.print(\"Humidity: \");\nSerial.println(humString);\nclient.publish(\"esp32\/humidity\", humString);<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Creating the Node-RED flow<\/h2>\n\n\n\n<p>Before creating the flow, you need to have installed in your Raspberry Pi:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-node-red-on-raspberry-pi\/\">Node-RED<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-node-red-dashboard\/\">Node-RED Dashboard<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\">Mosquitto Broker<\/a><\/li><\/ul>\n\n\n\n<p>After that, import the Node-RED flow provided. Go to the&nbsp;<a href=\"https:\/\/raw.githubusercontent.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/master\/Projects\/ESP32-MQTT\/Node_RED_Flow_ESP32_MQTT_Publish_Subscribe.txt\" target=\"_blank\" rel=\"noreferrer noopener\">GitHub repository<\/a>&nbsp;or click the figure below to see the raw file, and copy the code provided.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><a href=\"https:\/\/raw.githubusercontent.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/master\/Projects\/ESP32-MQTT\/Node_RED_Flow_ESP32_MQTT_Publish_Subscribe.txt\" target=\"_blank\" rel=\"noreferrer noopener\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"987\" height=\"94\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/import-node-red-mqtt-esp32.png?resize=987%2C94&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-62669\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/import-node-red-mqtt-esp32.png?w=987&amp;quality=100&amp;strip=all&amp;ssl=1 987w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/import-node-red-mqtt-esp32.png?resize=300%2C29&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/import-node-red-mqtt-esp32.png?resize=768%2C73&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/import-node-red-mqtt-esp32.png?resize=975%2C94&amp;quality=100&amp;strip=all&amp;ssl=1 975w\" sizes=\"(max-width: 987px) 100vw, 987px\" \/><\/a><\/figure><\/div>\n\n\n\n<p>Next, in the Node-RED window, at the top right corner, select the menu, and go to&nbsp;<strong>Import&nbsp;<\/strong>&nbsp;&gt;&nbsp;<strong>Clipboard<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"523\" height=\"291\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/11\/import-nodes.png?resize=523%2C291&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-45987\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/11\/import-nodes.png?w=523&amp;quality=100&amp;strip=all&amp;ssl=1 523w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/11\/import-nodes.png?resize=300%2C167&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 523px) 100vw, 523px\" \/><\/figure><\/div>\n\n\n\n<p>Then, paste the code provided and click&nbsp;<strong>Import<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"503\" height=\"337\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/01\/node-red-import-flow.png?resize=503%2C337&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-51645\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/01\/node-red-import-flow.png?w=503&amp;quality=100&amp;strip=all&amp;ssl=1 503w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/01\/node-red-import-flow.png?resize=300%2C201&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 503px) 100vw, 503px\" \/><\/figure><\/div>\n\n\n\n<p>The following nodes should load:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"506\" height=\"388\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/node-red-flow-mqtt-esp32-publish-subscribe.png?resize=506%2C388&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-62620\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/node-red-flow-mqtt-esp32-publish-subscribe.png?w=506&amp;quality=100&amp;strip=all&amp;ssl=1 506w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/node-red-flow-mqtt-esp32-publish-subscribe.png?resize=300%2C230&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 506px) 100vw, 506px\" \/><\/figure><\/div>\n\n\n\n<p>After making any changes, click the&nbsp;<strong>Deploy<\/strong>&nbsp;button to save all the changes.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"138\" height=\"40\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/06\/11_deploy_button.png?resize=138%2C40&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-40013\"\/><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Node-RED UI<\/h2>\n\n\n\n<p>Now, your Node-RED application is ready. To access Node-RED UI and see how your application looks, access any browser in your local network&nbsp;and type:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">http:\/\/<strong>Your_RPi_IP_address:1880<\/strong>\/ui<\/pre>\n\n\n\n<p>Your application should look as shown in the following figure. You can control the LED on and off with the switch or you can view temperature readings in a chart and the humidity values in a gauge.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"517\" height=\"699\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/node-red-ui-output-temperature-humidity.png?resize=517%2C699&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-62621\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/node-red-ui-output-temperature-humidity.png?w=517&amp;quality=100&amp;strip=all&amp;ssl=1 517w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/node-red-ui-output-temperature-humidity.png?resize=222%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 222w\" sizes=\"(max-width: 517px) 100vw, 517px\" \/><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>Watch the next video for a live demonstration:<\/p>\n\n\n<p style=\"text-align:center\"><iframe width=\"720\" height=\"405\" src=\"https:\/\/www.youtube.com\/embed\/vVmAH4UuEcA?rel=0\" frameborder=\"0\" allowfullscreen><\/iframe><\/p>\n\n\n\n<p>Open the Arduino IDE serial monitor to take a look at the MQTT messages being received and published.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"735\" height=\"464\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/serial-monitor-ide.png?resize=735%2C464&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-62622\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/serial-monitor-ide.png?w=735&amp;quality=100&amp;strip=all&amp;ssl=1 735w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/serial-monitor-ide.png?resize=300%2C189&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 735px) 100vw, 735px\" \/><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In summary, we\u2019ve shown you the basic concepts that allow you to turn on lights and monitor sensors with your ESP32 using Node-RED and the MQTT communication protocol. You can use this example to integrate in your own home automation system, control more outputs, or monitor other sensors.<\/p>\n\n\n\n<p><strong>You might also like reading:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><a href=\"https:\/\/randomnerdtutorials.com\/learn-esp32-with-arduino-ide\/\">Learn ESP32 with Arduino IDE Course<\/a><\/strong><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/alexa-echo-with-esp32-and-esp8266\/\">Alexa (Echo) with ESP32 and ESP8266 \u2013 Voice Controlled Relay<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/build-an-all-in-one-esp32-weather-station-shield\/\">Build an All-in-One ESP32 Weather Station Shield<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-publish-sensor-readings-to-google-sheets\/\">ESP32 Publish Sensor Readings to Google Sheets<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-dht11-dht22-temperature-humidity-web-server-arduino-ide\/\">ESP32 with DHT11 DHT22 Temperature Humidity Web Server<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-web-server-arduino-ide\/\">ESP32 Web Server with Arduino IDE<\/a><\/li><\/ul>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful.<\/p>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This project shows how to use MQTT communication protocol with the ESP32 to publish messages and subscribe to topics. As an example, we\u2019ll publish BME280 sensor readings to the Node-RED &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"ESP32 MQTT \u2013 Publish and Subscribe with Arduino IDE\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/esp32-mqtt-publish-subscribe-arduino-ide\/#more-62610\" aria-label=\"Read more about ESP32 MQTT \u2013 Publish and Subscribe with Arduino IDE\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":1,"featured_media":62623,"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":[276,281,277,299,273,264,268],"tags":[],"class_list":["post-62610","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp32","category-esp32-project","category-esp32-arduino-ide","category-0-esp32","category-node-red","category-project","category-raspberry-pi-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/05\/featured-image-esp32-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\/62610","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=62610"}],"version-history":[{"count":0,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/62610\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/62623"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=62610"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=62610"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=62610"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}