{"id":95590,"date":"2020-04-10T15:36:27","date_gmt":"2020-04-10T15:36:27","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=95590"},"modified":"2021-09-23T13:12:52","modified_gmt":"2021-09-23T13:12:52","slug":"micropython-mqtt-publish-dht11-dht22-esp32-esp8266","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/micropython-mqtt-publish-dht11-dht22-esp32-esp8266\/","title":{"rendered":"MicroPython: MQTT &#8211; Publish DHT11\/DHT22 Sensor Readings (ESP32\/ESP8266)"},"content":{"rendered":"\n<p>Learn how to program the ESP32 or ESP8266 boards with MicroPython to publish DHT11 or DHT22 sensor readings (temperature and humidity) via MQTT to any platform that supports MQTT or any MQTT client. As an example, we\u2019ll publish sensor readings to Node-RED Dashboard.<\/p>\n\n\n\n<div class=\"wp-block-image\"><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-ESP8266-DHT11-DHT22-MQTT-MicroPython.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython MQTT Publish DHT11 DHT22 Sensor Readings Temperature and Humidity with ESP32 ESP8266\" class=\"wp-image-95765\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-ESP8266-DHT11-DHT22-MQTT-MicroPython.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-ESP8266-DHT11-DHT22-MQTT-MicroPython.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-ESP8266-DHT11-DHT22-MQTT-MicroPython.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-ESP8266-DHT11-DHT22-MQTT-MicroPython.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\n<p class=\"rntbox rntclgray\"><strong>Recommended reading:<\/strong>&nbsp;<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<p><strong>Note: <\/strong> <em>this tutorial&nbsp;is compatible with both the ESP32 and ESP8266&nbsp;development boards.<\/em><\/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\n<figure class=\"wp-block-image size-large\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"890\" height=\"628\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/DHT-ESP32-ESP8266-MicroPython-MQTT-Project-Overview-f.png?resize=890%2C628&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"DHT ESP32 ESP8266 MicroPython MQTT Project Overview\" class=\"wp-image-95597\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/DHT-ESP32-ESP8266-MicroPython-MQTT-Project-Overview-f.png?w=890&amp;quality=100&amp;strip=all&amp;ssl=1 890w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/DHT-ESP32-ESP8266-MicroPython-MQTT-Project-Overview-f.png?resize=300%2C212&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/DHT-ESP32-ESP8266-MicroPython-MQTT-Project-Overview-f.png?resize=768%2C542&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 890px) 100vw, 890px\" \/><\/figure>\n\n\n\n<ul class=\"wp-block-list\"><li>The ESP requests temperature and humidity readings from the DHT11 or DHT22 sensor;<\/li><li>Temperature readings are published in the&nbsp;<strong>esp\/dht\/temperature<\/strong>&nbsp;topic;<\/li><li>Humidity readings are published in the&nbsp;<strong>esp\/dht\/humidity<\/strong> topic;<\/li><li>Node-RED is subscribed to those topics;<\/li><li>Node-RED receives the sensor readings and displays them on gauges;<\/li><li>You can receive the readings in any other platform that supports MQTT and handle the readings as you want.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>Before continuing with this tutorial, make sure you complete the following prerequisites:<\/p>\n\n\n\n<p>To follow this tutorial you need MicroPython firmware installed in your ESP32 or ESP8266 boards. You also need an IDE to write and upload the code to your board. We suggest using Thonny IDE or uPyCraft IDE:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Thonny IDE:<ul><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-thonny-micropython-python-ide-esp32-esp8266\/\">Installing and getting started with Thonny IDE<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/flashing-micropython-firmware-esptool-py-esp32-esp8266\/\">Flashing MicroPython Firmware with esptool.py<\/a><\/li><\/ul><\/li><li>uPyCraft IDE:<ul><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-micropython-esp32-esp8266\/\">Getting Started with uPyCraft IDE<\/a><\/li><li>Install uPyCraft IDE (<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-windows-pc-instructions\/\">Windows<\/a>,&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-mac-os-x-instructions\/\">Mac OS X<\/a>,&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/install-upycraft-ide-linux-ubuntu-instructions\/\">Linux<\/a>)<\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/flash-upload-micropython-firmware-esp32-esp8266\/\">Flash\/Upload MicroPython Firmware to ESP32 and ESP8266<\/a><\/li><\/ul><\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">MQTT Broker<\/h3>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"200\" height=\"197\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/01\/mosquitto-broker.png?resize=200%2C197&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Mosquitto MQTT Broker\" 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\n<p>To use MQTT, you need a broker. We&#8217;ll be using <a href=\"https:\/\/mosquitto.org\/\" target=\"_blank\" rel=\"noreferrer noopener\">Mosquitto broker<\/a> installed on a Raspberry Pi. Read&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Install Mosquitto Broker on Raspberry Pi<\/a>.<\/p>\n\n\n\n<p>If you&#8217;re not familiar with MQTT make sure you read our introductory tutorial:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/what-is-mqtt-and-how-it-works\/\" target=\"_blank\" rel=\"noreferrer noopener\">What is MQTT and How It Works<\/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\"><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\" target=\"_blank\">ESP32<\/a>&nbsp;(read&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/esp32-dev-board-wi-fi-bluetooth\/\" target=\"_blank\">Best ESP32 development boards<\/a>) or <a rel=\"noreferrer noopener\" aria-label=\"ESP8266 (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/esp8266-esp-12e-nodemcu-wi-fi-development-board\/\" target=\"_blank\">ESP8266<\/a><\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/dht11-temperature-humidity-sensor\/\" target=\"_blank\">DHT11<\/a> or <a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/dht22-temperature-humidity-sensor\/\" target=\"_blank\">DHT22<\/a> &#8211; <a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-dht11-dht22-micropython-temperature-humidity-sensor\/\">DHT with ESP32 Guide<\/a><\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\">4.7k Ohm resistor<\/a><\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/raspberry-pi-board\/\" target=\"_blank\">Raspberry Pi board<\/a>&nbsp;(read&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/best-raspberry-pi-starter-kits\/\" target=\"_blank\">Best Raspberry Pi Starter Kits<\/a>)<\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/microsd-card-raspberry-pi-16gb-class-10\/\" target=\"_blank\">MicroSD Card \u2013 16GB Class10<\/a><\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-power-supply\/\" target=\"_blank\">Raspberry Pi Power Supply (5V 2.5A)<\/a> <\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\">Jumper wires<\/a><\/li><li><a rel=\"noreferrer noopener\" href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\">Breadboard<\/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\">umqtttsimple Library<\/h2>\n\n\n\n<p>To use MQTT with the ESP32\/ESP8266 and MicroPython, we&#8217;ll use the <em>umqttsimple<\/em>.py library. Follow the next set of instructions for the IDE you&#8217;re using:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>A. Upload umqttsimple library with uPyCraft IDE<\/li><li>B. Upload umqttsimple library with Thonny IDE<\/li><\/ul>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\">try:\n    import usocket as socket\nexcept:\n    import socket\nimport ustruct as struct\nfrom ubinascii import hexlify\n\nclass MQTTException(Exception):\n    pass\n\nclass MQTTClient:\n\n    def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0,\n                 ssl=False, ssl_params={}):\n        if port == 0:\n            port = 8883 if ssl else 1883\n        self.client_id = client_id\n        self.sock = None\n        self.server = server\n        self.port = port\n        self.ssl = ssl\n        self.ssl_params = ssl_params\n        self.pid = 0\n        self.cb = None\n        self.user = user\n        self.pswd = password\n        self.keepalive = keepalive\n        self.lw_topic = None\n        self.lw_msg = None\n        self.lw_qos = 0\n        self.lw_retain = False\n\n    def _send_str(self, s):\n        self.sock.write(struct.pack(&quot;!H&quot;, len(s)))\n        self.sock.write(s)\n\n    def _recv_len(self):\n        n = 0\n        sh = 0\n        while 1:\n            b = self.sock.read(1)[0]\n            n |= (b &amp; 0x7f) &lt;&lt; sh\n            if not b &amp; 0x80:\n                return n\n            sh += 7\n\n    def set_callback(self, f):\n        self.cb = f\n\n    def set_last_will(self, topic, msg, retain=False, qos=0):\n        assert 0 &lt;= qos &lt;= 2\n        assert topic\n        self.lw_topic = topic\n        self.lw_msg = msg\n        self.lw_qos = qos\n        self.lw_retain = retain\n\n    def connect(self, clean_session=True):\n        self.sock = socket.socket()\n        addr = socket.getaddrinfo(self.server, self.port)[0][-1]\n        self.sock.connect(addr)\n        if self.ssl:\n            import ussl\n            self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)\n        premsg = bytearray(b&quot;\\x10\\0\\0\\0\\0\\0&quot;)\n        msg = bytearray(b&quot;\\x04MQTT\\x04\\x02\\0\\0&quot;)\n\n        sz = 10 + 2 + len(self.client_id)\n        msg[6] = clean_session &lt;&lt; 1\n        if self.user is not None:\n            sz += 2 + len(self.user) + 2 + len(self.pswd)\n            msg[6] |= 0xC0\n        if self.keepalive:\n            assert self.keepalive &lt; 65536\n            msg[7] |= self.keepalive &gt;&gt; 8\n            msg[8] |= self.keepalive &amp; 0x00FF\n        if self.lw_topic:\n            sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)\n            msg[6] |= 0x4 | (self.lw_qos &amp; 0x1) &lt;&lt; 3 | (self.lw_qos &amp; 0x2) &lt;&lt; 3\n            msg[6] |= self.lw_retain &lt;&lt; 5\n\n        i = 1\n        while sz &gt; 0x7f:\n            premsg[i] = (sz &amp; 0x7f) | 0x80\n            sz &gt;&gt;= 7\n            i += 1\n        premsg[i] = sz\n\n        self.sock.write(premsg, i + 2)\n        self.sock.write(msg)\n        #print(hex(len(msg)), hexlify(msg, &quot;:&quot;))\n        self._send_str(self.client_id)\n        if self.lw_topic:\n            self._send_str(self.lw_topic)\n            self._send_str(self.lw_msg)\n        if self.user is not None:\n            self._send_str(self.user)\n            self._send_str(self.pswd)\n        resp = self.sock.read(4)\n        assert resp[0] == 0x20 and resp[1] == 0x02\n        if resp[3] != 0:\n            raise MQTTException(resp[3])\n        return resp[2] &amp; 1\n\n    def disconnect(self):\n        self.sock.write(b&quot;\\xe0\\0&quot;)\n        self.sock.close()\n\n    def ping(self):\n        self.sock.write(b&quot;\\xc0\\0&quot;)\n\n    def publish(self, topic, msg, retain=False, qos=0):\n        pkt = bytearray(b&quot;\\x30\\0\\0\\0&quot;)\n        pkt[0] |= qos &lt;&lt; 1 | retain\n        sz = 2 + len(topic) + len(msg)\n        if qos &gt; 0:\n            sz += 2\n        assert sz &lt; 2097152\n        i = 1\n        while sz &gt; 0x7f:\n            pkt[i] = (sz &amp; 0x7f) | 0x80\n            sz &gt;&gt;= 7\n            i += 1\n        pkt[i] = sz\n        #print(hex(len(pkt)), hexlify(pkt, &quot;:&quot;))\n        self.sock.write(pkt, i + 1)\n        self._send_str(topic)\n        if qos &gt; 0:\n            self.pid += 1\n            pid = self.pid\n            struct.pack_into(&quot;!H&quot;, pkt, 0, pid)\n            self.sock.write(pkt, 2)\n        self.sock.write(msg)\n        if qos == 1:\n            while 1:\n                op = self.wait_msg()\n                if op == 0x40:\n                    sz = self.sock.read(1)\n                    assert sz == b&quot;\\x02&quot;\n                    rcv_pid = self.sock.read(2)\n                    rcv_pid = rcv_pid[0] &lt;&lt; 8 | rcv_pid[1]\n                    if pid == rcv_pid:\n                        return\n        elif qos == 2:\n            assert 0\n\n    def subscribe(self, topic, qos=0):\n        assert self.cb is not None, &quot;Subscribe callback is not set&quot;\n        pkt = bytearray(b&quot;\\x82\\0\\0\\0&quot;)\n        self.pid += 1\n        struct.pack_into(&quot;!BH&quot;, pkt, 1, 2 + 2 + len(topic) + 1, self.pid)\n        #print(hex(len(pkt)), hexlify(pkt, &quot;:&quot;))\n        self.sock.write(pkt)\n        self._send_str(topic)\n        self.sock.write(qos.to_bytes(1, &quot;little&quot;))\n        while 1:\n            op = self.wait_msg()\n            if op == 0x90:\n                resp = self.sock.read(4)\n                #print(resp)\n                assert resp[1] == pkt[2] and resp[2] == pkt[3]\n                if resp[3] == 0x80:\n                    raise MQTTException(resp[3])\n                return\n\n    # Wait for a single incoming MQTT message and process it.\n    # Subscribed messages are delivered to a callback previously\n    # set by .set_callback() method. Other (internal) MQTT\n    # messages processed internally.\n    def wait_msg(self):\n        res = self.sock.read(1)\n        self.sock.setblocking(True)\n        if res is None:\n            return None\n        if res == b&quot;&quot;:\n            raise OSError(-1)\n        if res == b&quot;\\xd0&quot;:  # PINGRESP\n            sz = self.sock.read(1)[0]\n            assert sz == 0\n            return None\n        op = res[0]\n        if op &amp; 0xf0 != 0x30:\n            return op\n        sz = self._recv_len()\n        topic_len = self.sock.read(2)\n        topic_len = (topic_len[0] &lt;&lt; 8) | topic_len[1]\n        topic = self.sock.read(topic_len)\n        sz -= topic_len + 2\n        if op &amp; 6:\n            pid = self.sock.read(2)\n            pid = pid[0] &lt;&lt; 8 | pid[1]\n            sz -= 2\n        msg = self.sock.read(sz)\n        self.cb(topic, msg)\n        if op &amp; 6 == 2:\n            pkt = bytearray(b&quot;\\x40\\x02\\0\\0&quot;)\n            struct.pack_into(&quot;!H&quot;, pkt, 2, pid)\n            self.sock.write(pkt)\n        elif op &amp; 6 == 4:\n            assert 0\n\n    # Checks whether a pending message from server is available.\n    # If not, returns immediately with None. Otherwise, does\n    # the same processing as wait_msg.\n    def check_msg(self):\n        self.sock.setblocking(False)\n        return self.wait_msg()\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/ESP-MicroPython\/raw\/master\/code\/MQTT\/umqttsimple.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">A. Upload umqttsimple library with uPyCraft IDE<\/h3>\n\n\n\n<p><strong>1.<\/strong> Create a new file by pressing the <strong>New File<\/strong> button.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"135\" height=\"41\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/10\/uPycraft-ide-tools-menu-new-file.png?resize=135%2C41&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-75063\"\/><\/figure><\/div>\n\n\n\n<p><strong>2.<\/strong> Copy the <em>umqttsimple<\/em> library code into it. You can access the <em>umqttsimple<\/em> library code in the following link:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/raw.githubusercontent.com\/RuiSantosdotme\/ESP-MicroPython\/master\/code\/MQTT\/umqttsimple.py\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/raw.githubusercontent.com\/RuiSantosdotme\/ESP-MicroPython\/master\/code\/MQTT\/umqttsimple.py<\/a><\/li><\/ul>\n\n\n\n<p><strong>3.<\/strong> Save the file by pressing the <strong>Save<\/strong> button.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"142\" height=\"47\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/10\/uPycraft-ide-tools-menu-save-file.png?resize=142%2C47&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-75064\"\/><\/figure><\/div>\n\n\n\n<p><strong>4.<\/strong> Call this new file \u201c<strong>umqttsimple.py<\/strong>\u201d and press <strong>ok<\/strong>.<\/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=\"305\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/12\/import-umqttsimple-library.png?resize=750%2C305&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-78499\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/12\/import-umqttsimple-library.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/12\/import-umqttsimple-library.png?resize=300%2C122&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<p><strong>5.<\/strong> Click the <strong>Download and Run<\/strong> button.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"238\" height=\"45\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/10\/uPycraft-ide-tools-menu-download-and-run.png?resize=238%2C45&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-75060\"\/><\/figure><\/div>\n\n\n\n<p><strong>6.<\/strong> The file should be saved on the <em>device<\/em> folder with the name \u201c<strong>umqttsimple.py<\/strong>\u201d as highlighted 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=\"468\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/12\/umqttsimple-library-installed.png?resize=750%2C468&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-78502\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/12\/umqttsimple-library-installed.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2018\/12\/umqttsimple-library-installed.png?resize=300%2C187&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n\n<p>Now, you can use the library functionalities in your code by importing the library.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">B. Upload umqttsimple library with Thonny IDE<\/h3>\n\n\n\n<p><strong>1.<\/strong> Copy the library code to a new file. The <a aria-label=\"umqttsimple library code can be found here (opens in a new tab)\" rel=\"noreferrer noopener\" href=\"https:\/\/raw.githubusercontent.com\/RuiSantosdotme\/ESP-MicroPython\/master\/code\/MQTT\/umqttsimple.py\" target=\"_blank\">umqttsimple library code can be found here<\/a>.<\/p>\n\n\n\n<p><strong>2.<\/strong> Go to <strong>File<\/strong> &gt; <strong>Save as&#8230;<\/strong><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"206\" height=\"294\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/10\/Thonny-IDE-ESP32-ESP8266-MicroPython-Save-file-library-to-device-save-as.png?resize=206%2C294&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Thonny IDE ESP32 ESP8266 MicroPython Save file library to device save as\" class=\"wp-image-99603\"\/><\/figure><\/div>\n\n\n\n<p>If the &#8220;Save as&#8230;&#8221; menu is missing, check that you have properly set up Thonny IDE as in the following tutorial:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-thonny-micropython-python-ide-esp32-esp8266\/\">Getting Started with Thonny MicroPython (Python) IDE for ESP32 and ESP8266<\/a><\/li><\/ul>\n\n\n\n<p><strong>3.<\/strong> Select save to &#8220;<strong>MicroPython device<\/strong>&#8220;:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"220\" height=\"202\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/10\/Thonny-IDE-ESP32-ESP8266-MicroPython-Save-file-library-to-device-select.png?resize=220%2C202&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Thonny IDE ESP32 ESP8266 MicroPython Save file library to device select\" class=\"wp-image-99605\"\/><\/figure><\/div>\n\n\n\n<p><strong>4.<\/strong> Name your file as <em>umqttsimple.py<\/em> and press the OK button:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"553\" height=\"263\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/10\/umqttsimple-library-new-MicroPython-file-Thonny-IDE.png?resize=553%2C263&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"umqttsimple library new MicroPython file Thonny IDE\" class=\"wp-image-99632\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/10\/umqttsimple-library-new-MicroPython-file-Thonny-IDE.png?w=553&amp;quality=100&amp;strip=all&amp;ssl=1 553w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/10\/umqttsimple-library-new-MicroPython-file-Thonny-IDE.png?resize=300%2C143&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 553px) 100vw, 553px\" \/><\/figure><\/div>\n\n\n\n<p>And that&#8217;s it. The library was uploaded to your board. To make sure that it was uploaded successfully, go to File &gt; Save as&#8230; and select the MicroPython device. Your file should be listed there:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"553\" height=\"289\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/10\/umqttsimple-library-MicroPython-file-created-Thonny-IDE.png?resize=553%2C289&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"umqttsimple library MicroPython file created Thonny IDE\" class=\"wp-image-99631\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/10\/umqttsimple-library-MicroPython-file-created-Thonny-IDE.png?w=553&amp;quality=100&amp;strip=all&amp;ssl=1 553w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/10\/umqttsimple-library-MicroPython-file-created-Thonny-IDE.png?resize=300%2C157&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 553px) 100vw, 553px\" \/><\/figure><\/div>\n\n\n\n<p>After uploading the library to your board, you can use the library functionalities in your code by importing the library.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"> Schematic: ESP32 with DHT11\/DHT22<\/h2>\n\n\n\n<p>Wire the <a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-dht11-dht22-micropython-temperature-humidity-sensor\/\">DHT22 or DHT11<\/a> sensor to the ESP32 development board as shown in the following schematic diagram. <\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht_esp32_bb-1.png?resize=546%2C683&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython circuit diagram Schematic ESP32 with DHT11 DHT22 \" class=\"wp-image-84481\" width=\"546\" height=\"683\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht_esp32_bb-1.png?w=728&amp;quality=100&amp;strip=all&amp;ssl=1 728w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht_esp32_bb-1.png?resize=240%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 240w\" sizes=\"(max-width: 546px) 100vw, 546px\" \/><\/figure><\/div>\n\n\n\n<p>In this example, we\u2019re connecting the DHT data pin to <span class=\"rnthl rntcblue\">GPIO 14<\/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\"> Schematic: ESP8266 NodeMCU with DHT11\/DHT22 <\/h2>\n\n\n\n<p>If you&#8217;re using an ESP8266 NodeMCU, follow the next diagram instead.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht_esp8266_bb.png?resize=429%2C674&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MicroPython circuit diagram Schematic ESP8266 NodeMCU with DHT11 DHT22 \" class=\"wp-image-84482\" width=\"429\" height=\"674\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht_esp8266_bb.png?w=572&amp;quality=100&amp;strip=all&amp;ssl=1 572w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht_esp8266_bb.png?resize=191%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 191w\" sizes=\"(max-width: 429px) 100vw, 429px\" \/><\/figure><\/div>\n\n\n\n<p>In this example, we\u2019re connecting the DHT data pin to&nbsp;<span class=\"rnthl rntcblue\">GPIO 14<\/span> (D5). However, you can use any other suitable digital pin.<\/p>\n\n\n\n<p class=\"rntbox rntclgray\">Learn how to use the ESP8266 GPIOs with our guide:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/esp8266-pinout-reference-gpios\/\">ESP8266 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>After uploading the library to the ESP32 or ESP8266, copy the following code to the <em>main.py<\/em> file. It publishes the temperature and humidity on the <strong>esp\/dht\/temperature<\/strong> and <strong>esp\/dht\/humidity<\/strong> topics every 5 seconds.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete project details at https:\/\/RandomNerdTutorials.com\/micropython-mqtt-publish-dht11-dht22-esp32-esp8266\/\n\nimport time\nfrom umqttsimple import MQTTClient\nimport ubinascii\nimport machine\nimport micropython\nimport network\nimport esp\nfrom machine import Pin\nimport dht\nesp.osdebug(None)\nimport gc\ngc.collect()\n\nssid = 'REPLACE_WITH_YOUR_SSID'\npassword = 'REPLACE_WITH_YOUR_PASSWORD'\nmqtt_server = '192.168.1.XXX'\n#EXAMPLE IP ADDRESS or DOMAIN NAME\n#mqtt_server = '192.168.1.106'\n\nclient_id = ubinascii.hexlify(machine.unique_id())\n\ntopic_pub_temp = b'esp\/dht\/temperature'\ntopic_pub_hum = b'esp\/dht\/humidity'\n\nlast_message = 0\nmessage_interval = 5\n\nstation = network.WLAN(network.STA_IF)\n\nstation.active(True)\nstation.connect(ssid, password)\n\nwhile station.isconnected() == False:\n  pass\n\nprint('Connection successful')\n\nsensor = dht.DHT22(Pin(14))\n#sensor = dht.DHT11(Pin(14))\n\ndef connect_mqtt():\n  global client_id, mqtt_server\n  client = MQTTClient(client_id, mqtt_server)\n  #client = MQTTClient(client_id, mqtt_server, user=your_username, password=your_password)\n  client.connect()\n  print('Connected to %s MQTT broker' % (mqtt_server))\n  return client\n\ndef restart_and_reconnect():\n  print('Failed to connect to MQTT broker. Reconnecting...')\n  time.sleep(10)\n  machine.reset()\n\ndef read_sensor():\n  try:\n    sensor.measure()\n    temp = sensor.temperature()\n    # uncomment for Fahrenheit\n    #temp = temp * (9\/5) + 32.0\n    hum = sensor.humidity()\n    if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum, int)):\n      temp = (b'{0:3.1f},'.format(temp))\n      hum =  (b'{0:3.1f},'.format(hum))\n      return temp, hum\n    else:\n      return('Invalid sensor readings.')\n  except OSError as e:\n    return('Failed to read sensor.')\n\ntry:\n  client = connect_mqtt()\nexcept OSError as e:\n  restart_and_reconnect()\n\nwhile True:\n  try:\n    if (time.time() - last_message) &gt; message_interval:\n      temp, hum = read_sensor()\n      print(temp)\n      print(hum)\n      client.publish(topic_pub_temp, temp)\n      client.publish(topic_pub_hum, hum)\n      last_message = time.time()\n  except OSError as e:\n    restart_and_reconnect()\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP-MicroPython\/MQTT\/esp_dht_mqtt.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How the Code Works<\/h2>\n\n\n\n<p>Import the following libraries:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import time\nfrom umqttsimple import MQTTClient\nimport ubinascii\nimport machine\nimport micropython\nimport network\nimport esp\nfrom machine import Pin\nimport dht\nesp.osdebug(None)\nimport gc\ngc.collect()<\/code><\/pre>\n\n\n\n<p>In the following variables, you need to enter your network credentials and your broker IP address.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>ssid = 'REPLACE_WITH_YOUR_SSID'\npassword = 'REPLACE_WITH_YOUR_PASSWORD'\nmqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'<\/code><\/pre>\n\n\n\n<p>For example, our broker IP address is: 192.168.1.106.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>mqtt_server = '192.168.1.106'<\/code><\/pre>\n\n\n\n<p><strong>Note:<\/strong>&nbsp;read&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\" target=\"_blank\" rel=\"noreferrer noopener\">this tutorial<\/a>&nbsp;to see how to get your broker IP address.<\/p>\n\n\n\n<p>To create an MQTT client, we need to get the ESP unique ID. That\u2019s what we do in the following line (it is saved on the <span class=\"rnthl rntliteral\">client_id<\/span> variable).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>client_id = ubinascii.hexlify(machine.unique_id())<\/code><\/pre>\n\n\n\n<p>Next, create the topics you want your ESP to be publishing in. In our example, it will publish temperature on the <strong>esp\/dht\/temperature<\/strong> topic and humidity on the <strong>esp\/dht\/humidity<\/strong> topic.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>topic_pub_temp = b'esp\/dht\/temperature'\ntopic_pub_hum = b'esp\/dht\/humidity'<\/code><\/pre>\n\n\n\n<p>Then, create the following variables:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>last_message = 0\nmessage_interval = 5<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">last_message<\/span> variable will hold the last time a message was sent. The <span class=\"rnthl rntliteral\">message_interval<\/span> is the time between each message sent. Here, we\u2019re setting it to 5 seconds (this means a new message will be sent every 5 seconds). You can change it, if you want. <\/p>\n\n\n\n<p>After that, connect the ESP to your local network.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>station = network.WLAN(network.STA_IF)\n\nstation.active(True)\nstation.connect(ssid, password)\n\nwhile station.isconnected() == False:\n  pass\n\nprint('Connection successful')<\/code><\/pre>\n\n\n\n<p>Initialize the DHT sensor by creating a <span class=\"rnthl rntliteral\">dht<\/span> instance on <span class=\"rnthl rntcblue\">GPIO 4<\/span> as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>sensor = dht.DHT22(Pin(4))<\/code><\/pre>\n\n\n\n<p>If you\u2019re using a DHT11 sensor, uncomment the next line, and comment the previous one:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>sensor = dht.DHT11(Pin(4))<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Connect to MQTT Broker<\/h3>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">connect_mqtt()<\/span> function creates an MQTT Client and connects to your broker.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def connect_mqtt():\n  global client_id, mqtt_server\n  client = MQTTClient(client_id, mqtt_server)\n  #client = MQTTClient(client_id, mqtt_server, user=your_username, password=your_password)\n  client.connect()\n  print('Connected to %s MQTT broker' % (mqtt_server))\n  return client<\/code><\/pre>\n\n\n\n<p>If your MQTT broker requires username and password, you should use the following line to pass your broker username and password as arguments.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>client = MQTTClient(client_id, mqtt_server, user=your_username, password=your_password)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Restart and Reconnect<\/h3>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">restart_and_reconnect()<\/span> function resets the ESP32\/ESP8266 board. This function will be called if we&#8217;re not able to publish the readings via MQTT in case the broker disconnects.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def restart_and_reconnect():\n  print('Failed to connect to MQTT broker. Reconnecting...')\n  time.sleep(10)\n  machine.reset()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Read DHT Sensor<\/h3>\n\n\n\n<p>We created a function called <span class=\"rnthl rntliteral\">read_sensor()<\/span> that returns the current temperature and humidity from the DHT sensor and handles any exceptions, in case we&#8217;re not able to get readings from the sensor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def read_sensor():\n  try:\n    sensor.measure()\n    temp = sensor.temperature()\n    hum = sensor.humidity()\n    if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum, int)):\n      temp = (b'{0:3.1f},'.format(temp))\n      hum =  (b'{0:3.1f},'.format(hum))\n\n      # uncomment for Fahrenheit\n      #temp = temp * (9\/5) + 32.0\n      return temp, hum\n    else:\n      return('Invalid sensor readings.')\n  except OSError as e:\n    return('Failed to read sensor.')<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Publishing MQTT Messages<\/h3>\n\n\n\n<p>In the while loop, we publish new temperature and humidity readings every 5 seconds.<\/p>\n\n\n\n<p>First, we check if it is time to get new readings:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>if (time.time() - last_message) &gt; message_interval:<\/code><\/pre>\n\n\n\n<p>If it is, request new readings from the DHT sensor by calling the <span class=\"rnthl rntliteral\">read_sensor()<\/span> function. The temperature is saved on the <span class=\"rnthl rntliteral\">temp<\/span> variable and the humidity is saved on the <span class=\"rnthl rntliteral\">hum<\/span> variable.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>temp, hum = read_sensor()<\/code><\/pre>\n\n\n\n<p>Finally, publish the readings by using the <span class=\"rnthl rntliteral\">publish()<\/span> method on the <span class=\"rnthl rntliteral\">client<\/span> object. The <span class=\"rnthl rntliteral\">publish()<\/span> method accepts as arguments the topic and the message, as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>client.publish(topic_pub_temp, temp)\nclient.publish(topic_pub_hum, hum)<\/code><\/pre>\n\n\n\n<p>Finally, update the time when the last message was sent:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>last_message = time.time()<\/code><\/pre>\n\n\n\n<p>In case the ESP32 or ESP8266 disconnects from the broker, and we&#8217;re not able to publish the readings, call the <span class=\"rnthl rntliteral\">restart_and_reconnect()<\/span> function to reset the ESP board and try to reconnect to the broker.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except OSError as e:\n  restart_and_reconnect()<\/code><\/pre>\n\n\n\n<p>After uploading the code, you should get new sensor readings on the shell every 5 seconds.<\/p>\n\n\n\n<p>Now, go to the next section to prepare Node-RED to receive the readings the ESP is publishing.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Preparing Node-RED Dashboard<\/h2>\n\n\n\n<p>The ESP32 or ESP8266 is publishing temperature readings every 5 seconds on the <strong>esp\/dht\/temperature<\/strong> and <strong>esp\/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\"><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-node-red-on-raspberry-pi\/\">Getting Started with Node-RED on Raspberry Pi<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-node-red-dashboard\/\">Installing and Getting Started with Node-RED Dashboard<\/a><\/li><\/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\n<div class=\"wp-block-image\"><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\n<p>Click the MQTT node and edit its properties.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"504\" height=\"391\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/MQTT-In-Node-ESP32-ESP8266-Publish-Temperature-Humidity-Node-RED-Flow.png?resize=504%2C391&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"MQTT In Node ESP32 ESP8266 Publish Temperature Humidity Node-RED Flow\" class=\"wp-image-95636\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/MQTT-In-Node-ESP32-ESP8266-Publish-Temperature-Humidity-Node-RED-Flow.png?w=504&amp;quality=100&amp;strip=all&amp;ssl=1 504w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/MQTT-In-Node-ESP32-ESP8266-Publish-Temperature-Humidity-Node-RED-Flow.png?resize=300%2C233&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 504px) 100vw, 504px\" \/><\/figure><\/div>\n\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>esp\/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>esp\/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\n<div class=\"wp-block-image\"><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\n<p>Wire your nodes as shown below:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"469\" height=\"139\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-MQTT-Publish-DHT-Temperature-Humidity-Node-RED-Flow.png?resize=469%2C139&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP32 ESP8266 MQTT Publish DHT Temperature Humidity Node RED Flow\" class=\"wp-image-95635\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-MQTT-Publish-DHT-Temperature-Humidity-Node-RED-Flow.png?w=469&amp;quality=100&amp;strip=all&amp;ssl=1 469w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-MQTT-Publish-DHT-Temperature-Humidity-Node-RED-Flow.png?resize=300%2C89&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 469px) 100vw, 469px\" \/><\/figure><\/div>\n\n\n\n<p>Finally, deploy your flow (press the button on the upper right corner).<\/p>\n\n\n\n<div class=\"wp-block-image\"><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\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;59f95d85.b6f0b4&quot;,&quot;type&quot;:&quot;mqtt in&quot;,&quot;z&quot;:&quot;b01416d3.f69f38&quot;,&quot;name&quot;:&quot;&quot;,&quot;topic&quot;:&quot;esp\/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;:910,&quot;y&quot;:340,&quot;wires&quot;:[[&quot;2babfd19.559212&quot;]]},{&quot;id&quot;:&quot;2babfd19.559212&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;:1210,&quot;y&quot;:340,&quot;wires&quot;:[]},{&quot;id&quot;:&quot;b9aa2398.37ca3&quot;,&quot;type&quot;:&quot;mqtt in&quot;,&quot;z&quot;:&quot;b01416d3.f69f38&quot;,&quot;name&quot;:&quot;&quot;,&quot;topic&quot;:&quot;esp\/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;:900,&quot;y&quot;:420,&quot;wires&quot;:[[&quot;d0f75e86.1c9ae&quot;]]},{&quot;id&quot;:&quot;d0f75e86.1c9ae&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;:1200,&quot;y&quot;:420,&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;BME280&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\/ESP-MicroPython\/MQTT\/esp_dht_mqtt_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\n<div class=\"wp-block-image\"><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 ESP8266 MQTT Publish Temperature Humidity DHT11 DHT22 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\n<p>That&#8217;s it! You have your ESP32 or ESP8266 boards publishing DHT temperature and humidity readings to Node-RED via MQTT using MicroPython.<\/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 IoT devices. In this tutorial you\u2019ve learned how to publish temperature and humidity readings from a DHT sensor with the ESP32 and ESP8266 using MicroPython 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 href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-dht11-dht22-micropython-temperature-humidity-sensor\/\">DHT11 or DHT22 sensor<\/a>, you can use any other sensor like a <a href=\"https:\/\/randomnerdtutorials.com\/micropython-ds18b20-esp32-esp8266\/\">DS18B20 temperature sensor<\/a> or <a href=\"https:\/\/randomnerdtutorials.com\/micropython-bme280-esp32-esp8266\/\">BME280 sensor<\/a>.<\/p>\n\n\n\n<p>We have other projects\/tutorials related with the DHT sensor that you may also like:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-dht11-dht22-micropython-temperature-humidity-sensor\/\">MicroPython: ESP32\/ESP8266 with DHT11\/DHT22 Temperature and Humidity Sensor<\/a><\/li><li><a href=\"https:\/\/randomnerdtutorials.com\/micropython-esp32-esp8266-dht11-dht22-web-server\/\">MicroPython: ESP32\/ESP8266 with DHT11\/DHT22 Web Server<\/a><\/li><\/ul>\n\n\n\n<p class=\"rntbox rntclgray\">Learn more about MicroPython with our eBook: <a href=\"https:\/\/randomnerdtutorials.com\/micropython-programming-with-esp32-and-esp8266\/\">MicroPython Programming using ESP32\/ESP8266<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to program the ESP32 or ESP8266 boards with MicroPython to publish DHT11 or DHT22 sensor readings (temperature and humidity) via MQTT to any platform that supports MQTT or &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"MicroPython: MQTT &#8211; Publish DHT11\/DHT22 Sensor Readings (ESP32\/ESP8266)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/micropython-mqtt-publish-dht11-dht22-esp32-esp8266\/#more-95590\" aria-label=\"Read more about MicroPython: MQTT &#8211; Publish DHT11\/DHT22 Sensor Readings (ESP32\/ESP8266)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":95765,"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,214,310,309,264],"tags":[],"class_list":["post-95590","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-esp32","category-esp8266","category-micropython","category-0-esp32-micropython","category-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2020\/04\/ESP32-ESP8266-DHT11-DHT22-MQTT-MicroPython.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\/95590","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=95590"}],"version-history":[{"count":1,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/95590\/revisions"}],"predecessor-version":[{"id":106728,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/95590\/revisions\/106728"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/95765"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=95590"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=95590"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=95590"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}