{"id":95552,"date":"2020-04-06T09:42:24","date_gmt":"2020-04-06T09:42:24","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=95552"},"modified":"2024-06-12T10:27:52","modified_gmt":"2024-06-12T10:27:52","slug":"esp32-mqtt-publish-dht11-dht22-arduino","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/esp32-mqtt-publish-dht11-dht22-arduino\/","title":{"rendered":"ESP32 MQTT &#8211; Publish DHT11\/DHT22 Temperature and Humidity Readings (Arduino IDE)"},"content":{"rendered":"\n<p>Learn how to publish temperature and humidity readings from a DHT11 or DHT22 sensor via MQTT with the ESP32 to any platform that supports MQTT or any MQTT client. As an example, we&#8217;ll publish sensor readings to Node-RED Dashboard and the ESP32 will be programmed 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\/2020\/04\/ESP32-DHT11-DHT22-Temperature-Humidity-Sensor-MQTT-Publish-Arduino-IDE-Node-RED.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 MQTT Publish DHT22 or DHT11 Sensor Readings Arduino IDE\" class=\"wp-image-95553\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-DHT11-DHT22-Temperature-Humidity-Sensor-MQTT-Publish-Arduino-IDE-Node-RED.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-DHT11-DHT22-Temperature-Humidity-Sensor-MQTT-Publish-Arduino-IDE-Node-RED.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-DHT11-DHT22-Temperature-Humidity-Sensor-MQTT-Publish-Arduino-IDE-Node-RED.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-DHT11-DHT22-Temperature-Humidity-Sensor-MQTT-Publish-Arduino-IDE-Node-RED.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\"><strong>Recommended reading:<\/strong> <a href=\"https:\/\/randomnerdtutorials.com\/what-is-mqtt-and-how-it-works\/\">What is MQTT and How It Works<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Project Overview<\/h2>\n\n\n\n<p>The following diagram shows a high-level overview of the project we&#8217;ll build.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-MQTT-DHT11-DHT22-Node-RED.png?quality=100&#038;strip=all&#038;ssl=1\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"888\" height=\"586\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-MQTT-DHT11-DHT22-Node-RED.png?resize=888%2C586&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"DHT11\/DHT22 Publish Readings Node-Red MQTT How it works and project overview\" class=\"wp-image-95554\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-MQTT-DHT11-DHT22-Node-RED.png?w=888&amp;quality=100&amp;strip=all&amp;ssl=1 888w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-MQTT-DHT11-DHT22-Node-RED.png?resize=300%2C198&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-MQTT-DHT11-DHT22-Node-RED.png?resize=768%2C507&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 888px) 100vw, 888px\" \/><\/a><\/figure><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>The ESP32 requests temperature and humidity readings from the DHT11 or DHT22 sensor;<\/li>\n\n\n\n<li>Temperature readings are published in the\u00a0<strong>esp32\/dht\/temperature<\/strong>\u00a0topic;<\/li>\n\n\n\n<li>Humidity readings are published in the\u00a0<strong>esp32\/dht\/humidity<\/strong> topic;<\/li>\n\n\n\n<li>Node-RED is subscribed those topics;<\/li>\n\n\n\n<li>Node-RED receives the sensor readings and displays them on gauges;<\/li>\n\n\n\n<li>You can receive the readings in any other platform that supports MQTT and handle the readings as you want.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>Before proceeding with this tutorial, make sure you check the following prerequisites.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Arduino IDE<\/h3>\n\n\n\n<p>We&#8217;ll program the ESP32 using Arduino IDE, so make sure you have the ESP32 add-on installed.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/installing-the-esp32-board-in-arduino-ide-windows-instructions\/\">Installing the ESP32 Board in Arduino IDE (Windows, Mac OS X, Linux)<\/a><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">MQTT Broker<\/h3>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><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=\"Installing Mosquitto MQTT broker Raspberry Pi\" 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>To use MQTT, you need a broker. We\u2019ll be using&nbsp;<a href=\"https:\/\/mosquitto.org\/\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\">Mosquitto broker<\/a>&nbsp;installed on a Raspberry Pi. Read&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\" target=\"_blank\">How to Install Mosquitto Broker on Raspberry Pi<\/a>.<\/p>\n\n\n\n<p>You can use any other MQTT broker, including a cloud MQTT broker. We&#8217;ll show you how to do that in the code later on.<\/p>\n\n\n\n<p>If you\u2019re not familiar with MQTT make sure you read our introductory tutorial:&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/randomnerdtutorials.com\/what-is-mqtt-and-how-it-works\/\" target=\"_blank\">What is MQTT and How It Works<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">MQTT Libraries<\/h3>\n\n\n\n<p>To use MQTT with the ESP32 we&#8217;ll use the <a href=\"https:\/\/github.com\/marvinroger\/async-mqtt-client\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\">Async MQTT Client Library<\/a>.<\/p>\n\n\n\n<p><strong>Installing the Async MQTT Client Library<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a aria-label=\" (opens in a new tab)\" href=\"https:\/\/github.com\/marvinroger\/async-mqtt-client\/archive\/master.zip\" target=\"_blank\" rel=\"noreferrer noopener\">Click here to download the Async MQTT client library<\/a>. You should have a .zip folder in your Downloads folder<\/li>\n\n\n\n<li>Unzip the .zip folder and you should get\u00a0<strong>async-mqtt-client-master<\/strong>\u00a0folder<\/li>\n\n\n\n<li>Rename your folder from\u00a0<del><strong>async-mqtt-client-master<\/strong><\/del>\u00a0to\u00a0<strong>async_mqtt_client<\/strong><\/li>\n\n\n\n<li>Move the\u00a0<strong>async_mqtt_client<\/strong>\u00a0folder to your Arduino IDE installation libraries folder<\/li>\n\n\n\n<li>Finally, re-open your Arduino IDE<\/li>\n<\/ol>\n\n\n\n<p>Alternatively, you can go to <strong>Sketch <\/strong>&gt; <strong>Include Library<\/strong> &gt; <strong>Add . ZIP<\/strong> library and select the library you&#8217;ve just downloaded.<\/p>\n\n\n\n<p><strong>Installing the Async TCP Library<\/strong><\/p>\n\n\n\n<p>To use MQTT with the ESP, you also need the&nbsp;<a href=\"https:\/\/github.com\/me-no-dev\/AsyncTCP\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\">Async TCP library<\/a>.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a aria-label=\" (opens in a new tab)\" href=\"https:\/\/github.com\/me-no-dev\/AsyncTCP\/archive\/master.zip\" target=\"_blank\" rel=\"noreferrer noopener\">Click here to download the Async TCP client library<\/a>. You should have a .zip folder in your Downloads folder<\/li>\n\n\n\n<li>Unzip the .zip folder and you should get\u00a0<strong>AsyncTCP-master<\/strong>\u00a0folder<\/li>\n\n\n\n<li>Rename your folder from\u00a0<del><strong>AsyncTCP-master<\/strong><\/del>\u00a0to\u00a0<strong>AsyncTCP<\/strong><\/li>\n\n\n\n<li>Move the\u00a0<strong>AsyncTCP\u00a0<\/strong>folder to your Arduino IDE installation libraries folder<\/li>\n\n\n\n<li>Finally, re-open your Arduino IDE<\/li>\n<\/ol>\n\n\n\n<p>Alternatively, you can go to <strong>Sketch <\/strong>&gt; <strong>Include Library<\/strong> &gt; <strong>Add . ZIP<\/strong> library and select the library you&#8217;ve just downloaded. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">DHT Sensor Libraries<\/h3>\n\n\n\n<p>To read from the DHT sensor, we\u2019ll use the&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/github.com\/adafruit\/DHT-sensor-library\" target=\"_blank\">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>1. 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>2. 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>3. 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>After installing the libraries, restart your Arduino IDE.<\/p>\n\n\n\n<p class=\"rntbox rntclblue\">To learn more about the DHT11 or DHT22 temperature sensor, read our guide: <a href=\"https:\/\/randomnerdtutorials.com\/esp32-dht11-dht22-temperature-humidity-sensor-arduino-ide\/\">ESP32 with DHT11\/DHT22 Temperature and Humidity Sensor using Arduino IDE<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Parts Required<\/h3>\n\n\n\n<p>For this tutorial you need the following parts:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\" target=\"_blank\" rel=\"noreferrer noopener\">ESP32<\/a>\u00a0(read\u00a0<a href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\" target=\"_blank\" rel=\"noreferrer noopener\">Best ESP32 development boards<\/a>)<\/li>\n\n\n\n<li><a aria-label=\"DHT11 (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/dht11-temperature-humidity-sensor\/\" target=\"_blank\" rel=\"noreferrer noopener\">DHT11<\/a> or <a aria-label=\"DHT22 (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/dht22-temperature-humidity-sensor\/\" target=\"_blank\" rel=\"noreferrer noopener\">DHT22<\/a> &#8211; <a href=\"https:\/\/randomnerdtutorials.com\/esp32-dht11-dht22-temperature-humidity-sensor-arduino-ide\/\">DHT with ESP32 Guide<\/a><\/li>\n\n\n\n<li><a aria-label=\"4.7k Ohm resistor (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noreferrer noopener\">4.7k Ohm resistor<\/a><\/li>\n\n\n\n<li><a aria-label=\" (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/raspberry-pi-board\/\" target=\"_blank\" rel=\"noreferrer noopener\">Raspberry Pi board<\/a>\u00a0(read\u00a0<a aria-label=\" (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/best-raspberry-pi-starter-kits\/\" target=\"_blank\" rel=\"noreferrer noopener\">Best Raspberry Pi Starter Kits<\/a>)<\/li>\n\n\n\n<li><a aria-label=\" (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/microsd-card-raspberry-pi-16gb-class-10\/\" target=\"_blank\" rel=\"noreferrer noopener\">MicroSD Card \u2013 16GB Class10<\/a><\/li>\n\n\n\n<li><a aria-label=\" (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-power-supply\/\" target=\"_blank\" rel=\"noreferrer noopener\">Raspberry Pi Power Supply (5V 2.5A)<\/a> <\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noreferrer noopener\">Jumper wires<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\" rel=\"noreferrer noopener\">Breadboard<\/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\">Schematic Diagram<\/h2>\n\n\n\n<p>Wire the DHT11 or DHT22 to the ESP32 as shown in the following schematic diagram with the data pin connected to <span class=\"rnthl rntcblue\">GPIO 4<\/span>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"714\" height=\"892\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht_esp32_bb.png?resize=714%2C892&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"DHT11 DHT22 wiring to ESP32 schematic diagram\" class=\"wp-image-84352\" style=\"width:465px;height:582px\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht_esp32_bb.png?w=714&amp;quality=100&amp;strip=all&amp;ssl=1 714w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht_esp32_bb.png?resize=240%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 240w\" sizes=\"(max-width: 714px) 100vw, 714px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclgray\"><strong>Note: <\/strong> if you have a DHT sensor in a breakout board, it comes with only three pins and with an internal pull-up resistor on pin 2, so you don&#8217;t need to connect the resistor. You just need to wire VCC, data and GND. <\/p>\n\n\n\n<p>In this example, we\u2019re connecting the DHT data pin to <span class=\"rnthl rntcblue\">GPIO 4<\/span>. However, you can use any other suitable digital pin.<\/p>\n\n\n\n<p class=\"rntbox rntclgray\">Learn how to use the ESP32 GPIOs with our guide:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/esp32-pinout-reference-gpios\/\">ESP32 Pinout Reference: Which GPIO pins should you use?<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Code<\/h2>\n\n\n\n<p>Copy the following code to your Arduino IDE. To make it work for you, you need to insert your network credentials as well as the MQTT broker details.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*\n  Rui Santos &amp; Sara Santos - Random Nerd Tutorials\n  Complete project details at https:\/\/RandomNerdTutorials.com\/esp32-mqtt-publish-dht11-dht22-arduino\/\n  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.\n  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n*\/\n#include &quot;DHT.h&quot;\n#include &lt;WiFi.h&gt;\nextern &quot;C&quot; {\n  #include &quot;freertos\/FreeRTOS.h&quot;\n  #include &quot;freertos\/timers.h&quot;\n}\n#include &lt;AsyncMqttClient.h&gt;\n\n#define WIFI_SSID &quot;REPLACE_WITH_YOUR_SSID&quot;\n#define WIFI_PASSWORD &quot;REPLACE_WITH_YOUR_PASSWORD&quot;\n\n\/\/ Raspberry Pi Mosquitto MQTT Broker\n#define MQTT_HOST IPAddress(192, 168, 1, XXX)\n\/\/ For a cloud MQTT broker, type the domain name\n\/\/#define MQTT_HOST &quot;example.com&quot;\n#define MQTT_PORT 1883\n\n\/\/ Temperature MQTT Topics\n#define MQTT_PUB_TEMP &quot;esp32\/dht\/temperature&quot;\n#define MQTT_PUB_HUM  &quot;esp32\/dht\/humidity&quot;\n\n\/\/ Digital pin connected to the DHT sensor\n#define DHTPIN 4  \n\n\/\/ Uncomment whatever DHT sensor type you're using\n\/\/#define DHTTYPE DHT11   \/\/ DHT 11\n#define DHTTYPE DHT22   \/\/ DHT 22  (AM2302), AM2321\n\/\/#define DHTTYPE DHT21   \/\/ DHT 21 (AM2301)   \n\n\/\/ Initialize DHT sensor\nDHT dht(DHTPIN, DHTTYPE);\n\n\/\/ Variables to hold sensor readings\nfloat temp;\nfloat hum;\n\nAsyncMqttClient mqttClient;\nTimerHandle_t mqttReconnectTimer;\nTimerHandle_t wifiReconnectTimer;\n\nunsigned long previousMillis = 0;   \/\/ Stores last time temperature was published\nconst long interval = 10000;        \/\/ Interval at which to publish sensor readings\n\nvoid connectToWifi() {\n  Serial.println(&quot;Connecting to Wi-Fi...&quot;);\n  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);\n}\n\nvoid connectToMqtt() {\n  Serial.println(&quot;Connecting to MQTT...&quot;);\n  mqttClient.connect();\n}\n\nvoid WiFiEvent(WiFiEvent_t event) {\n  Serial.printf(&quot;[WiFi-event] event: %d\\n&quot;, event);\n  switch(event) {\n    case ARDUINO_EVENT_WIFI_STA_GOT_IP:\n      Serial.println(&quot;WiFi connected&quot;);\n      Serial.println(&quot;IP address: &quot;);\n      Serial.println(WiFi.localIP());\n      connectToMqtt();\n      break;\n    case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:\n      Serial.println(&quot;WiFi lost connection&quot;);\n      xTimerStop(mqttReconnectTimer, 0); \/\/ ensure we don't reconnect to MQTT while reconnecting to Wi-Fi\n      xTimerStart(wifiReconnectTimer, 0);\n      break;\n  }\n}\n\nvoid onMqttConnect(bool sessionPresent) {\n  Serial.println(&quot;Connected to MQTT.&quot;);\n  Serial.print(&quot;Session present: &quot;);\n  Serial.println(sessionPresent);\n}\n\nvoid onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {\n  Serial.println(&quot;Disconnected from MQTT.&quot;);\n  if (WiFi.isConnected()) {\n    xTimerStart(mqttReconnectTimer, 0);\n  }\n}\n\n\/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) {\n  Serial.println(&quot;Subscribe acknowledged.&quot;);\n  Serial.print(&quot;  packetId: &quot;);\n  Serial.println(packetId);\n  Serial.print(&quot;  qos: &quot;);\n  Serial.println(qos);\n}\nvoid onMqttUnsubscribe(uint16_t packetId) {\n  Serial.println(&quot;Unsubscribe acknowledged.&quot;);\n  Serial.print(&quot;  packetId: &quot;);\n  Serial.println(packetId);\n}*\/\n\nvoid onMqttPublish(uint16_t packetId) {\n  Serial.print(&quot;Publish acknowledged.&quot;);\n  Serial.print(&quot;  packetId: &quot;);\n  Serial.println(packetId);\n}\n\nvoid setup() {\n  Serial.begin(115200);\n  Serial.println();\n\n  dht.begin();\n  \n  mqttReconnectTimer = xTimerCreate(&quot;mqttTimer&quot;, pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast&lt;TimerCallbackFunction_t&gt;(connectToMqtt));\n  wifiReconnectTimer = xTimerCreate(&quot;wifiTimer&quot;, pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast&lt;TimerCallbackFunction_t&gt;(connectToWifi));\n\n  WiFi.onEvent(WiFiEvent);\n\n  mqttClient.onConnect(onMqttConnect);\n  mqttClient.onDisconnect(onMqttDisconnect);\n  \/\/mqttClient.onSubscribe(onMqttSubscribe);\n  \/\/mqttClient.onUnsubscribe(onMqttUnsubscribe);\n  mqttClient.onPublish(onMqttPublish);\n  mqttClient.setServer(MQTT_HOST, MQTT_PORT);\n  \/\/ If your broker requires authentication (username and password), set them below\n  \/\/mqttClient.setCredentials(&quot;REPlACE_WITH_YOUR_USER&quot;, &quot;REPLACE_WITH_YOUR_PASSWORD&quot;);\n  connectToWifi();\n}\n\nvoid loop() {\n  unsigned long currentMillis = millis();\n  \/\/ Every X number of seconds (interval = 10 seconds) \n  \/\/ it publishes a new MQTT message\n  if (currentMillis - previousMillis &gt;= interval) {\n    \/\/ Save the last time a new reading was published\n    previousMillis = currentMillis;\n    \/\/ New DHT sensor readings\n    hum = dht.readHumidity();\n    \/\/ Read temperature as Celsius (the default)\n    temp = dht.readTemperature();\n    \/\/ Read temperature as Fahrenheit (isFahrenheit = true)\n    \/\/temp = dht.readTemperature(true);\n\n    \/\/ Check if any reads failed and exit early (to try again).\n    if (isnan(temp) || isnan(hum)) {\n      Serial.println(F(&quot;Failed to read from DHT sensor!&quot;));\n      return;\n    }\n    \n    \/\/ Publish an MQTT message on topic esp32\/dht\/temperature\n    uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());                            \n    Serial.printf(&quot;Publishing on topic %s at QoS 1, packetId: %i&quot;, MQTT_PUB_TEMP, packetIdPub1);\n    Serial.printf(&quot;Message: %.2f \\n&quot;, temp);\n\n    \/\/ Publish an MQTT message on topic esp32\/dht\/humidity\n    uint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());                            \n    Serial.printf(&quot;Publishing on topic %s at QoS 1, packetId %i: &quot;, MQTT_PUB_HUM, packetIdPub2);\n    Serial.printf(&quot;Message: %.2f \\n&quot;, hum);\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\/ESP32_MQTT\/ESP32_DHT.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>The following section imports all the required libraries.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#include \"DHT.h\"\n#include &lt;WiFi.h&gt;\nextern \"C\" {\n  #include \"freertos\/FreeRTOS.h\"\n  #include \"freertos\/timers.h\"\n}\n#include &lt;AsyncMqttClient.h&gt;<\/code><\/pre>\n\n\n\n<p>Include your network credentials on the following lines.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define WIFI_SSID \"REPLACE_WITH_YOUR_SSID\"\n#define WIFI_PASSWORD \"REPLACE_WITH_YOUR_PASSWORD\"<\/code><\/pre>\n\n\n\n<p>Insert the Raspberry Pi IP address, so that the ESP32 connects to your broker.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define MQTT_HOST IPAddress(192, 168, 1, 106)<\/code><\/pre>\n\n\n\n<p>If you&#8217;re using a cloud MQTT broker, insert the broker domain name, for example:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define MQTT_HOST \"example.com\"<\/code><\/pre>\n\n\n\n<p>Define the MQTT port.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define MQTT_PORT 1883<\/code><\/pre>\n\n\n\n<p>The temperature and humidity will be published on the following topics:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define MQTT_PUB_TEMP \"esp32\/dht\/temperature\"\n#define MQTT_PUB_HUM  \"esp32\/dht\/humidity\"<\/code><\/pre>\n\n\n\n<p>Define the GPIO that the DHT sensor data pin is connected to. In our case, it is connected to <span class=\"rnthl rntcblue\">GPIO 4<\/span>.<\/p>\n\n\n\n<p>Uncomment the DHT sensor type you&#8217;re using. In our example, we&#8217;re using the DHT22.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/#define DHTTYPE DHT11   \/\/ DHT 11\n#define DHTTYPE DHT22     \/\/ DHT 22 (AM2302), AM2321\n\/\/#define DHTTYPE DHT21   \/\/ DHT 21 (AM2301)<\/code><\/pre>\n\n\n\n<p>Initialize the DHT sensor on the pin and type defined earlier.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>DHT dht(DHTPIN, DHTTYPE);<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">temp<\/span> and <span class=\"rnthl rntliteral\">hum<\/span> variables will hold the temperature and humidity values from the DHT22 sensor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>float temp;\nfloat hum;<\/code><\/pre>\n\n\n\n<p>Create an <span class=\"rnthl rntliteral\">AsyncMqttClient<\/span> object called <span class=\"rnthl rntliteral\">mqttClient<\/span> to handle the MQTT client and timers to reconnect to your MQTT broker and router when it disconnects.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>AsyncMqttClient mqttClient;\nTimerHandle_t mqttReconnectTimer;\nTimerHandle_t wifiReconnectTimer;<\/code><\/pre>\n\n\n\n<p>Then, create some auxiliary timer variables to publish the readings every 10 seconds. You can change the delay time on the <span class=\"rnthl rntliteral\">interval<\/span> variable.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>unsigned long previousMillis = 0;  \/\/ Stores last time temperature was published\nconst long interval = 10000;       \/\/ Interval at which to publish sensor readings<\/code><\/pre>\n\n\n\n<p class=\"rntbox rntclblue\"><strong>Note: <\/strong> the DHT11 and DHT22 have a low sampling rate. You can only request DHT11 readings every second, or every two seconds for the DHT22.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">MQTT functions: connect to Wi-Fi, connect to MQTT, and Wi-Fi events<\/h3>\n\n\n\n<p>We haven\u2019t added any comments to the functions defined in the next code section. Those functions come with the Async Mqtt Client library. The function\u2019s names are pretty self-explanatory.<\/p>\n\n\n\n<p>For example, the <span class=\"rnthl rntliteral\">connectToWifi()<\/span> connects your ESP32 to your router:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void connectToWifi() {\n  Serial.println(\"Connecting to Wi-Fi...\");\n  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);\n}<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">connectToMqtt()<\/span> connects your ESP32 to your MQTT broker:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void connectToMqtt() {\n  Serial.println(\"Connecting to MQTT\u2026\");\n  mqttClient.connect();\n }<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">WiFiEvent()<\/span> function is responsible for handling the Wi-Fi events. For example, after a successful connection with the router and MQTT broker, it prints the ESP32 IP address. On the other hand, if the connection is lost, it starts a timer and tries to reconnect.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void WiFiEvent(WiFiEvent_t event) {\n  Serial.printf(\"&#091;WiFi-event] event: %d\\n\", event);\n  switch(event) {\n    case ARDUINO_EVENT_WIFI_STA_GOT_IP:\n      Serial.println(\"WiFi connected\");\n      Serial.println(\"IP address: \");\n      Serial.println(WiFi.localIP());\n      connectToMqtt();\n      break;\n    case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:\n      Serial.println(\"WiFi lost connection\");\n      xTimerStop(mqttReconnectTimer, 0);\n      xTimerStart(wifiReconnectTimer, 0);\n      break;\n  }\n}<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">onMqttConnect()<\/span> function runs after starting a session with the broker.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onMqttConnect(bool sessionPresent) {\n  Serial.println(\"Connected to MQTT.\");\n  Serial.print(\"Session present: \");\n  Serial.println(sessionPresent);\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">MQTT functions: disconnect and publish<\/h3>\n\n\n\n<p>If the ESP32 loses connection with the MQTT broker, it calls the <span class=\"rnthl rntliteral\">onMqttDisconnect<\/span> function that prints that message in the serial monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {\n  Serial.println(\"Disconnected from MQTT.\");\n  if (WiFi.isConnected()) { \n    xTimerStart(mqttReconnectTimer, 0);\n  }\n}<\/code><\/pre>\n\n\n\n<p>When you publish a message to an MQTT topic, the <span class=\"rnthl rntliteral\">onMqttPublish()<\/span> function is called. It prints the packet id in the Serial Monitor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onMqttPublish(uint16_t packetId) {\n  Serial.println(\"Publish acknowledged.\");\n  Serial.print(\"  packetId: \");\n  Serial.println(packetId);\n}<\/code><\/pre>\n\n\n\n<p>Basically, all these functions that we\u2019ve just mentioned are callback functions. So, they are executed asynchronously.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">setup()<\/h3>\n\n\n\n<p>Now, let\u2019s proceed to the <span class=\"rnthl rntliteral\">setup()<\/span>. Initialize the DHT sensor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>dht.begin();<\/code><\/pre>\n\n\n\n<p>The next two lines create timers that will allow both the MQTT broker and Wi-Fi connection to reconnect, in case the connection is lost.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>mqttReconnectTimer = xTimerCreate(\"mqttTimer\", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast&lt;TimerCallbackFunction_t&gt;(connectToMqtt));\nwifiReconnectTimer = xTimerCreate(\"wifiTimer\", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast&lt;TimerCallbackFunction_t&gt;(connectToWifi));<\/code><\/pre>\n\n\n\n<p>The following line assigns a callback function, so when the ESP32 connects to your Wi-Fi, it will execute the <span class=\"rnthl rntliteral\">WiFiEvent()<\/span> function to print the details described earlier.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>WiFi.onEvent(WiFiEvent);<\/code><\/pre>\n\n\n\n<p>Finally, assign all the callback functions. This means that these functions will be executed automatically when needed. For example, when the ESP32 connects to the broker, it automatically calls the <span class=\"rnthl rntliteral\">onMqttConnect()<\/span> function, and so on.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>mqttClient.onConnect(onMqttConnect);\nmqttClient.onDisconnect(onMqttDisconnect);\n\/\/mqttClient.onSubscribe(onMqttSubscribe);\n\/\/mqttClient.onUnsubscribe(onMqttUnsubscribe);\nmqttClient.onPublish(onMqttPublish);\nmqttClient.setServer(MQTT_HOST, MQTT_PORT);<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Broker Authentication<\/h4>\n\n\n\n<p>If your broker requires authentication, uncomment the following line and insert your credentials (username and password).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>mqttClient.setCredentials(\"REPlACE_WITH_YOUR_USER\", \"REPLACE_WITH_YOUR_PASSWORD\");<\/code><\/pre>\n\n\n\n<p>Finally, connect to Wi-Fi.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>connectToWifi();<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">loop()<\/h2>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">loop()<\/span>, you create a timer that will allow you to get new temperature and humidity readings from the DHT sensor and publishing them on the corresponding topic every 10 seconds.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>unsigned long currentMillis = millis();\n\/\/ Every X number of seconds (interval = 10 seconds) \n\/\/ it publishes a new MQTT message\nif (currentMillis - previousMillis &gt;= interval) {\n  \/\/ Save the last time a new reading was published\n  previousMillis = currentMillis;\n  \/\/ New DHT sensor readings\n  hum = dht.readHumidity();\n  \/\/ Read temperature as Celsius (the default)\n  temp = dht.readTemperature();\n  \/\/ Read temperature as Fahrenheit (isFahrenheit = true)\n  \/\/temp = dht.readTemperature(true);<\/code><\/pre>\n\n\n\n<p class=\"rntbox rntclblue\">Learn more about getting readings from the DHT11 or DHT22 sensors: <a href=\"https:\/\/randomnerdtutorials.com\/esp32-dht11-dht22-temperature-humidity-sensor-arduino-ide\/\">ESP32 with DHT11\/DHT22 Temperature and Humidity Sensor using Arduino IDE<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Publishing to topics<\/h3>\n\n\n\n<p>To publish the readings on the corresponding MQTT topics, use the next lines:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());\nuint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());<\/code><\/pre>\n\n\n\n<p>Basically, use the <span class=\"rnthl rntliteral\">publish()<\/span> method on the <span class=\"rnthl rntliteral\">mqttClient<\/span> object to publish data on a topic. The <span class=\"rnthl rntliteral\">publish()<\/span> method accepts the following arguments, in order:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>MQTT topic (const char*)<\/li>\n\n\n\n<li>QoS (uint8_t): quality of service &#8211; it can be 0, 1 or 2<\/li>\n\n\n\n<li>retain flag (bool): retain flag<\/li>\n\n\n\n<li>payload (const char*) &#8211; in this case, the payload corresponds to the sensor reading<\/li>\n<\/ul>\n\n\n\n<p>The QoS (quality of service) is a way to guarantee that the message is delivered. It can be one of the following levels:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>0<\/strong>: the message will be delivered once or not at all. The message is not acknowledged. There is no possibility of duplicated messages;<\/li>\n\n\n\n<li><strong>1<\/strong>: the message will be delivered at least once, but may be delivered more than once;<\/li>\n\n\n\n<li><strong>2<\/strong>: the message is always delivered exactly once;<\/li>\n\n\n\n<li><a aria-label=\" (opens in a new tab)\" href=\"https:\/\/www.ibm.com\/support\/knowledgecenter\/en\/SSFKSJ_8.0.0\/com.ibm.mq.dev.doc\/q029090_.htm\" target=\"_blank\" rel=\"noreferrer noopener\">Learn about MQTT QoS.<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Uploading the code<\/h2>\n\n\n\n<p>With your Raspberry Pi powered on and running the Mosquitto MQTT broker, upload the code to your ESP32.<\/p>\n\n\n\n<p>Open the Serial Monitor at a baud rate of 115200 and you&#8217;ll see that the ESP32 starts publishing messages on the topics we&#8217;ve defined previously.<\/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=\"839\" height=\"522\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-Publish-MQTT-DHT11-DHT22-Temperature-Serial-Monitor.png?resize=839%2C522&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Publish MQTT DHT11 DHT22 Temperature Humidity Serial Monitor\" class=\"wp-image-95563\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-Publish-MQTT-DHT11-DHT22-Temperature-Serial-Monitor.png?w=839&amp;quality=100&amp;strip=all&amp;ssl=1 839w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-Publish-MQTT-DHT11-DHT22-Temperature-Serial-Monitor.png?resize=300%2C187&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-Publish-MQTT-DHT11-DHT22-Temperature-Serial-Monitor.png?resize=768%2C478&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 839px) 100vw, 839px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Preparing Node-RED Dashboard<\/h2>\n\n\n\n<p>The ESP32 is publishing temperature readings every 10 seconds on the <strong>esp32\/dht\/temperature<\/strong> and <strong>esp32\/dht\/humidity<\/strong> topics. Now, you can use any dashboard that supports MQTT or any other device that supports MQTT to subscribe to those topics and receive the readings.<\/p>\n\n\n\n<p>As an example, we&#8217;ll create a simple flow using Node-RED to subscribe to those topics and display the readings on gauges.<\/p>\n\n\n\n<p>If you don&#8217;t have Node-RED installed, follow the next tutorials:<\/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\/\">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\/\">Installing and Getting Started with Node-RED Dashboard<\/a><\/li>\n<\/ul>\n\n\n\n<p>Having Node-RED running on your Raspberry Pi, go to your Raspberry Pi IP address followed by :1880.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>http:&#47;&#47;raspberry-pi-ip-address:1880<\/code><\/pre>\n\n\n\n<p>The Node-RED interface should open. Drag two MQTT in nodes, and two gauge nodes to the flow.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"266\" height=\"103\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/0-ESP32-DHT11-DHT22-Arduino-IDE.png?resize=266%2C103&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 DHT11 DHT22 Arduino IDE\" class=\"wp-image-95558\"\/><\/figure><\/div>\n\n\n<p>Click the MQTT node and edit its properties.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"503\" height=\"369\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/1-MQTT-In-Node-ESP32-Publish-Temperature-Humidity-Node-RED-Flow.png?resize=503%2C369&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MQTT In Node ESP32 Publish Temperature Humidity Node-RED Flow\" class=\"wp-image-95559\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/1-MQTT-In-Node-ESP32-Publish-Temperature-Humidity-Node-RED-Flow.png?w=503&amp;quality=100&amp;strip=all&amp;ssl=1 503w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/1-MQTT-In-Node-ESP32-Publish-Temperature-Humidity-Node-RED-Flow.png?resize=300%2C220&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 503px) 100vw, 503px\" \/><\/figure><\/div>\n\n\n<p>The Server field refers to the MQTT broker. In our case, the MQTT broker is the Raspberry Pi, so it is set to localhost:1883. If you&#8217;re using a Cloud MQTT broker, you should change that field. <\/p>\n\n\n\n<p>Insert the topic you want to be subscribed to and the QoS. This previous MQTT node is subscribed to the <strong>esp32\/dht\/temperature<\/strong> topic. <\/p>\n\n\n\n<p>Click on the other MQTT in node and edit its properties with the same server, but for the other topic: <strong>esp32\/dht\/humidity<\/strong>. <\/p>\n\n\n\n<p>Click on the gauge nodes and edit its properties for each reading. The following node is set for the temperature readings. Edit the other chart node for the humidity readings.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"497\" height=\"603\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/2-ESP32-Gauge-Temperature-Humidity-Node-RED-Flow.png?resize=497%2C603&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 Gauge Temperature Humidity Node-RED Flow\" class=\"wp-image-95560\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/2-ESP32-Gauge-Temperature-Humidity-Node-RED-Flow.png?w=497&amp;quality=100&amp;strip=all&amp;ssl=1 497w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/2-ESP32-Gauge-Temperature-Humidity-Node-RED-Flow.png?resize=247%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 247w\" sizes=\"(max-width: 497px) 100vw, 497px\" \/><\/figure><\/div>\n\n\n<p>Wire your nodes as shown below:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"475\" height=\"141\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/3-ESP32-MQTT-Publish-Temperature-Humidity-Node-RED-Flow.png?resize=475%2C141&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 MQTT Publish Temperature Humidity Node-RED Flow\" class=\"wp-image-95561\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/3-ESP32-MQTT-Publish-Temperature-Humidity-Node-RED-Flow.png?w=475&amp;quality=100&amp;strip=all&amp;ssl=1 475w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/3-ESP32-MQTT-Publish-Temperature-Humidity-Node-RED-Flow.png?resize=300%2C89&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 475px) 100vw, 475px\" \/><\/figure><\/div>\n\n\n<p>Finally, deploy your flow (press the button on the upper right corner).<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><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=\"Deploy Node-RED button\" class=\"wp-image-40013\"\/><\/figure><\/div>\n\n\n<p>Alternatively, you can go to <strong>Menu <\/strong>&gt; <strong>Import <\/strong>and copy the following to your <strong>Clipboard<\/strong> to create your Node-RED flow.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">[{&quot;id&quot;:&quot;5a45b8da.52b0d8&quot;,&quot;type&quot;:&quot;mqtt in&quot;,&quot;z&quot;:&quot;b01416d3.f69f38&quot;,&quot;name&quot;:&quot;&quot;,&quot;topic&quot;:&quot;esp32\/dht\/temperature&quot;,&quot;qos&quot;:&quot;1&quot;,&quot;datatype&quot;:&quot;auto&quot;,&quot;broker&quot;:&quot;8db3fac0.99dd48&quot;,&quot;x&quot;:300,&quot;y&quot;:60,&quot;wires&quot;:[[&quot;3042e15e.80a4ee&quot;]]},{&quot;id&quot;:&quot;3042e15e.80a4ee&quot;,&quot;type&quot;:&quot;ui_gauge&quot;,&quot;z&quot;:&quot;b01416d3.f69f38&quot;,&quot;name&quot;:&quot;&quot;,&quot;group&quot;:&quot;37de8fe8.46846&quot;,&quot;order&quot;:2,&quot;width&quot;:0,&quot;height&quot;:0,&quot;gtype&quot;:&quot;gage&quot;,&quot;title&quot;:&quot;Temperature&quot;,&quot;label&quot;:&quot;\u00baC&quot;,&quot;format&quot;:&quot;{{value}}&quot;,&quot;min&quot;:0,&quot;max&quot;:&quot;40&quot;,&quot;colors&quot;:[&quot;#00b500&quot;,&quot;#f7df09&quot;,&quot;#ca3838&quot;],&quot;seg1&quot;:&quot;&quot;,&quot;seg2&quot;:&quot;&quot;,&quot;x&quot;:590,&quot;y&quot;:60,&quot;wires&quot;:[]},{&quot;id&quot;:&quot;8ff168f0.0c74a8&quot;,&quot;type&quot;:&quot;mqtt in&quot;,&quot;z&quot;:&quot;b01416d3.f69f38&quot;,&quot;name&quot;:&quot;&quot;,&quot;topic&quot;:&quot;esp32\/dht\/humidity&quot;,&quot;qos&quot;:&quot;1&quot;,&quot;datatype&quot;:&quot;auto&quot;,&quot;broker&quot;:&quot;8db3fac0.99dd48&quot;,&quot;x&quot;:290,&quot;y&quot;:140,&quot;wires&quot;:[[&quot;29251f29.6687c&quot;]]},{&quot;id&quot;:&quot;29251f29.6687c&quot;,&quot;type&quot;:&quot;ui_gauge&quot;,&quot;z&quot;:&quot;b01416d3.f69f38&quot;,&quot;name&quot;:&quot;&quot;,&quot;group&quot;:&quot;37de8fe8.46846&quot;,&quot;order&quot;:2,&quot;width&quot;:0,&quot;height&quot;:0,&quot;gtype&quot;:&quot;gage&quot;,&quot;title&quot;:&quot;Humidity&quot;,&quot;label&quot;:&quot;%&quot;,&quot;format&quot;:&quot;{{value}}&quot;,&quot;min&quot;:&quot;30&quot;,&quot;max&quot;:&quot;100&quot;,&quot;colors&quot;:[&quot;#53a4e6&quot;,&quot;#1d78a9&quot;,&quot;#4e38c9&quot;],&quot;seg1&quot;:&quot;&quot;,&quot;seg2&quot;:&quot;&quot;,&quot;x&quot;:580,&quot;y&quot;:140,&quot;wires&quot;:[]},{&quot;id&quot;:&quot;8db3fac0.99dd48&quot;,&quot;type&quot;:&quot;mqtt-broker&quot;,&quot;z&quot;:&quot;&quot;,&quot;name&quot;:&quot;&quot;,&quot;broker&quot;:&quot;localhost&quot;,&quot;port&quot;:&quot;1883&quot;,&quot;clientid&quot;:&quot;&quot;,&quot;usetls&quot;:false,&quot;compatmode&quot;:false,&quot;keepalive&quot;:&quot;60&quot;,&quot;cleansession&quot;:true,&quot;birthTopic&quot;:&quot;&quot;,&quot;birthQos&quot;:&quot;0&quot;,&quot;birthPayload&quot;:&quot;&quot;,&quot;closeTopic&quot;:&quot;&quot;,&quot;closeQos&quot;:&quot;0&quot;,&quot;closePayload&quot;:&quot;&quot;,&quot;willTopic&quot;:&quot;&quot;,&quot;willQos&quot;:&quot;0&quot;,&quot;willPayload&quot;:&quot;&quot;},{&quot;id&quot;:&quot;37de8fe8.46846&quot;,&quot;type&quot;:&quot;ui_group&quot;,&quot;z&quot;:&quot;&quot;,&quot;name&quot;:&quot;DHT&quot;,&quot;tab&quot;:&quot;53b8c8f9.cfbe48&quot;,&quot;order&quot;:1,&quot;disp&quot;:true,&quot;width&quot;:&quot;6&quot;,&quot;collapse&quot;:false},{&quot;id&quot;:&quot;53b8c8f9.cfbe48&quot;,&quot;type&quot;:&quot;ui_tab&quot;,&quot;z&quot;:&quot;&quot;,&quot;name&quot;:&quot;Home&quot;,&quot;icon&quot;:&quot;dashboard&quot;,&quot;order&quot;:2,&quot;disabled&quot;:false,&quot;hidden&quot;:false}]\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\/ESP32_MQTT\/ESP32_DHT_Flow.txt\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>Go to your Raspberry Pi IP address followed by <em>:1880\/ui<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>http:&#47;&#47;raspberry-pi-ip-address:1880\/ui<\/code><\/pre>\n\n\n\n<p>You should get access to the current DHT temperature and humidity readings on the Dashboard. You can use other dashboard-type nodes to display the readings on different ways.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"517\" height=\"618\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/4-ESP32-MQTT-Publish-Temperature-Humidity-Node-RED-Dashboard.png?resize=517%2C618&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 MQTT Publish Temperature Humidity Node-RED Dashboard\" class=\"wp-image-95562\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/4-ESP32-MQTT-Publish-Temperature-Humidity-Node-RED-Dashboard.png?w=517&amp;quality=100&amp;strip=all&amp;ssl=1 517w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/4-ESP32-MQTT-Publish-Temperature-Humidity-Node-RED-Dashboard.png?resize=251%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 251w\" sizes=\"(max-width: 517px) 100vw, 517px\" \/><\/figure><\/div>\n\n\n<p>That&#8217;s it! You have your ESP32 board publishing DHT temperature and humidity readings to Node-RED via MQTT.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>MQTT is a great communication protocol to exchange small amounts of data between devices. In this tutorial you&#8217;ve learned how to publish temperature and humidity readings from a DHT sensor with the ESP32 to different MQTT topics. Then, you can use any device or home automation platform to subscribe to those topics and receive the readings. <\/p>\n\n\n\n<p>Instead of a <a rel=\"noreferrer noopener\" aria-label=\"DHT11 (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/dht11-temperature-humidity-sensor\/\" target=\"_blank\">DHT11<\/a> or <a rel=\"noreferrer noopener\" aria-label=\"DHT22 (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/dht22-temperature-humidity-sensor\/\" target=\"_blank\">DHT22<\/a> sensor, you can use any other sensor like a <a rel=\"noreferrer noopener\" aria-label=\"DS18B20 temperature sensor (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/ds18b20-temperature-sensor-2\/\" target=\"_blank\">DS18B20 temperature sensor<\/a> or <a rel=\"noreferrer noopener\" aria-label=\"BME280 temperature, humidity and pressure sensor (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/bme280-sensor-module\/\" target=\"_blank\">BME280 sensor<\/a>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-mqtt-publish-ds18b20-temperature-arduino\/\">ESP32 MQTT \u2013 Publish DS18B20 Temperature Readings<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-mqtt-publish-bme280-arduino\/\">ESP32 MQTT \u2013 Publish BME280 Temperature, Humidity and Pressure Readings<\/a><\/li>\n<\/ul>\n\n\n\n<p>We hope you&#8217;ve found this tutorial useful. If you want to learn more about the ESP32, take a look at our resources:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/learn-esp32-with-arduino-ide\/\">Learn ESP32 with Arduino IDE<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-programming-with-esp32-and-esp8266\/\">MicroPython Programming with ESP32 and ESP8266<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-esp32\/\">More ESP32 Projects&#8230;<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to publish temperature and humidity readings from a DHT11 or DHT22 sensor via MQTT with the ESP32 to any platform that supports MQTT or any MQTT client. As &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"ESP32 MQTT &#8211; Publish DHT11\/DHT22 Temperature and Humidity Readings (Arduino IDE)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/esp32-mqtt-publish-dht11-dht22-arduino\/#more-95552\" aria-label=\"Read more about ESP32 MQTT &#8211; Publish DHT11\/DHT22 Temperature and Humidity Readings (Arduino IDE)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":95553,"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,264],"tags":[],"class_list":["post-95552","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp32","category-esp32-project","category-esp32-arduino-ide","category-0-esp32","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-DHT11-DHT22-Temperature-Humidity-Sensor-MQTT-Publish-Arduino-IDE-Node-RED.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\/95552","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\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=95552"}],"version-history":[{"count":1,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/95552\/revisions"}],"predecessor-version":[{"id":158835,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/95552\/revisions\/158835"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/95553"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=95552"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=95552"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=95552"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}