MicroPython: MQTT – Publish DHT11/DHT22 Sensor Readings (ESP32/ESP8266)

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’ll publish sensor readings to Node-RED Dashboard.

MicroPython MQTT Publish DHT11 DHT22 Sensor Readings Temperature and Humidity with ESP32 ESP8266

Recommended reading: What is MQTT and How It Works

Note: this tutorial is compatible with both the ESP32 and ESP8266 development boards.

Project Overview

The following diagram shows a high-level overview of the project we’ll build.

DHT ESP32 ESP8266 MicroPython MQTT Project Overview
  • The ESP requests temperature and humidity readings from the DHT11 or DHT22 sensor;
  • Temperature readings are published in the esp/dht/temperature topic;
  • Humidity readings are published in the esp/dht/humidity topic;
  • Node-RED is subscribed to those topics;
  • Node-RED receives the sensor readings and displays them on gauges;
  • You can receive the readings in any other platform that supports MQTT and handle the readings as you want.

Prerequisites

Before continuing with this tutorial, make sure you complete the following prerequisites:

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:

MQTT Broker

Mosquitto MQTT Broker

To use MQTT, you need a broker. We’ll be using Mosquitto broker installed on a Raspberry Pi. Read How to Install Mosquitto Broker on Raspberry Pi.

If you’re not familiar with MQTT make sure you read our introductory tutorial: What is MQTT and How It Works

Parts Required

For this tutorial you need the following parts:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

umqtttsimple Library

To use MQTT with the ESP32/ESP8266 and MicroPython, we’ll use the umqttsimple.py library. Follow the next set of instructions for the IDE you’re using:

  • A. Upload umqttsimple library with uPyCraft IDE
  • B. Upload umqttsimple library with Thonny IDE
try:
    import usocket as socket
except:
    import socket
import ustruct as struct
from ubinascii import hexlify

class MQTTException(Exception):
    pass

class MQTTClient:

    def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0,
                 ssl=False, ssl_params={}):
        if port == 0:
            port = 8883 if ssl else 1883
        self.client_id = client_id
        self.sock = None
        self.server = server
        self.port = port
        self.ssl = ssl
        self.ssl_params = ssl_params
        self.pid = 0
        self.cb = None
        self.user = user
        self.pswd = password
        self.keepalive = keepalive
        self.lw_topic = None
        self.lw_msg = None
        self.lw_qos = 0
        self.lw_retain = False

    def _send_str(self, s):
        self.sock.write(struct.pack("!H", len(s)))
        self.sock.write(s)

    def _recv_len(self):
        n = 0
        sh = 0
        while 1:
            b = self.sock.read(1)[0]
            n |= (b & 0x7f) << sh
            if not b & 0x80:
                return n
            sh += 7

    def set_callback(self, f):
        self.cb = f

    def set_last_will(self, topic, msg, retain=False, qos=0):
        assert 0 <= qos <= 2
        assert topic
        self.lw_topic = topic
        self.lw_msg = msg
        self.lw_qos = qos
        self.lw_retain = retain

    def connect(self, clean_session=True):
        self.sock = socket.socket()
        addr = socket.getaddrinfo(self.server, self.port)[0][-1]
        self.sock.connect(addr)
        if self.ssl:
            import ussl
            self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
        premsg = bytearray(b"\x10\0\0\0\0\0")
        msg = bytearray(b"\x04MQTT\x04\x02\0\0")

        sz = 10 + 2 + len(self.client_id)
        msg[6] = clean_session << 1
        if self.user is not None:
            sz += 2 + len(self.user) + 2 + len(self.pswd)
            msg[6] |= 0xC0
        if self.keepalive:
            assert self.keepalive < 65536
            msg[7] |= self.keepalive >> 8
            msg[8] |= self.keepalive & 0x00FF
        if self.lw_topic:
            sz += 2 + len(self.lw_topic) + 2 + len(self.lw_msg)
            msg[6] |= 0x4 | (self.lw_qos & 0x1) << 3 | (self.lw_qos & 0x2) << 3
            msg[6] |= self.lw_retain << 5

        i = 1
        while sz > 0x7f:
            premsg[i] = (sz & 0x7f) | 0x80
            sz >>= 7
            i += 1
        premsg[i] = sz

        self.sock.write(premsg, i + 2)
        self.sock.write(msg)
        #print(hex(len(msg)), hexlify(msg, ":"))
        self._send_str(self.client_id)
        if self.lw_topic:
            self._send_str(self.lw_topic)
            self._send_str(self.lw_msg)
        if self.user is not None:
            self._send_str(self.user)
            self._send_str(self.pswd)
        resp = self.sock.read(4)
        assert resp[0] == 0x20 and resp[1] == 0x02
        if resp[3] != 0:
            raise MQTTException(resp[3])
        return resp[2] & 1

    def disconnect(self):
        self.sock.write(b"\xe0\0")
        self.sock.close()

    def ping(self):
        self.sock.write(b"\xc0\0")

    def publish(self, topic, msg, retain=False, qos=0):
        pkt = bytearray(b"\x30\0\0\0")
        pkt[0] |= qos << 1 | retain
        sz = 2 + len(topic) + len(msg)
        if qos > 0:
            sz += 2
        assert sz < 2097152
        i = 1
        while sz > 0x7f:
            pkt[i] = (sz & 0x7f) | 0x80
            sz >>= 7
            i += 1
        pkt[i] = sz
        #print(hex(len(pkt)), hexlify(pkt, ":"))
        self.sock.write(pkt, i + 1)
        self._send_str(topic)
        if qos > 0:
            self.pid += 1
            pid = self.pid
            struct.pack_into("!H", pkt, 0, pid)
            self.sock.write(pkt, 2)
        self.sock.write(msg)
        if qos == 1:
            while 1:
                op = self.wait_msg()
                if op == 0x40:
                    sz = self.sock.read(1)
                    assert sz == b"\x02"
                    rcv_pid = self.sock.read(2)
                    rcv_pid = rcv_pid[0] << 8 | rcv_pid[1]
                    if pid == rcv_pid:
                        return
        elif qos == 2:
            assert 0

    def subscribe(self, topic, qos=0):
        assert self.cb is not None, "Subscribe callback is not set"
        pkt = bytearray(b"\x82\0\0\0")
        self.pid += 1
        struct.pack_into("!BH", pkt, 1, 2 + 2 + len(topic) + 1, self.pid)
        #print(hex(len(pkt)), hexlify(pkt, ":"))
        self.sock.write(pkt)
        self._send_str(topic)
        self.sock.write(qos.to_bytes(1, "little"))
        while 1:
            op = self.wait_msg()
            if op == 0x90:
                resp = self.sock.read(4)
                #print(resp)
                assert resp[1] == pkt[2] and resp[2] == pkt[3]
                if resp[3] == 0x80:
                    raise MQTTException(resp[3])
                return

    # Wait for a single incoming MQTT message and process it.
    # Subscribed messages are delivered to a callback previously
    # set by .set_callback() method. Other (internal) MQTT
    # messages processed internally.
    def wait_msg(self):
        res = self.sock.read(1)
        self.sock.setblocking(True)
        if res is None:
            return None
        if res == b"":
            raise OSError(-1)
        if res == b"\xd0":  # PINGRESP
            sz = self.sock.read(1)[0]
            assert sz == 0
            return None
        op = res[0]
        if op & 0xf0 != 0x30:
            return op
        sz = self._recv_len()
        topic_len = self.sock.read(2)
        topic_len = (topic_len[0] << 8) | topic_len[1]
        topic = self.sock.read(topic_len)
        sz -= topic_len + 2
        if op & 6:
            pid = self.sock.read(2)
            pid = pid[0] << 8 | pid[1]
            sz -= 2
        msg = self.sock.read(sz)
        self.cb(topic, msg)
        if op & 6 == 2:
            pkt = bytearray(b"\x40\x02\0\0")
            struct.pack_into("!H", pkt, 2, pid)
            self.sock.write(pkt)
        elif op & 6 == 4:
            assert 0

    # Checks whether a pending message from server is available.
    # If not, returns immediately with None. Otherwise, does
    # the same processing as wait_msg.
    def check_msg(self):
        self.sock.setblocking(False)
        return self.wait_msg()

View raw code

A. Upload umqttsimple library with uPyCraft IDE

1. Create a new file by pressing the New File button.

2. Copy the umqttsimple library code into it. You can access the umqttsimple library code in the following link:

3. Save the file by pressing the Save button.

4. Call this new file “umqttsimple.py” and press ok.

5. Click the Download and Run button.

6. The file should be saved on the device folder with the name “umqttsimple.py” as highlighted in the figure below.

Now, you can use the library functionalities in your code by importing the library.

B. Upload umqttsimple library with Thonny IDE

1. Copy the library code to a new file. The umqttsimple library code can be found here.

2. Save that file as umqttsimple.py.

3. Go to Device Upload current script with the current name.

Upload umqtt library esp32 esp8266 micropython Thonny IDE

And that’s it. The library was uploaded to your board. To make sure that it was uploaded successfully, in the Shell you can type:

%lsdevice

It should return the files currently saved on your board. One of them should be the umqttsimple.py file.

Upload umqtt library esp32 esp8266 micropython thonny ide

After uploading the library to your board, you can use the library functionalities in your code by importing the library.

Schematic: ESP32 with DHT11/DHT22

Wire the DHT22 or DHT11 sensor to the ESP32 development board as shown in the following schematic diagram.

MicroPython circuit diagram Schematic ESP32 with DHT11 DHT22

In this example, we’re connecting the DHT data pin to GPIO 14. However, you can use any other suitable digital pin.

Learn how to use the ESP32 GPIOs with our guide: ESP32 Pinout Reference: Which GPIO pins should you use?

Schematic: ESP8266 NodeMCU with DHT11/DHT22

If you’re using an ESP8266 NodeMCU, follow the next diagram instead.

MicroPython circuit diagram Schematic ESP8266 NodeMCU with DHT11 DHT22

In this example, we’re connecting the DHT data pin to GPIO 14 (D5). However, you can use any other suitable digital pin.

Learn how to use the ESP8266 GPIOs with our guide: ESP8266 Pinout Reference: Which GPIO pins should you use?

Code

After uploading the library to the ESP32 or ESP8266, copy the following code to the main.py file. It publishes the temperature and humidity on the esp/dht/temperature and esp/dht/humidity topics every 5 seconds.

# Complete project details at https://RandomNerdTutorials.com/micropython-mqtt-publish-dht11-dht22-esp32-esp8266/

import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
from machine import Pin
import dht
esp.osdebug(None)
import gc
gc.collect()

ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
mqtt_server = '192.168.1.XXX'
#EXAMPLE IP ADDRESS or DOMAIN NAME
#mqtt_server = '192.168.1.106'

client_id = ubinascii.hexlify(machine.unique_id())

topic_pub_temp = b'esp/dht/temperature'
topic_pub_hum = b'esp/dht/humidity'

last_message = 0
message_interval = 5

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

print('Connection successful')

sensor = dht.DHT22(Pin(14))
#sensor = dht.DHT11(Pin(14))

def connect_mqtt():
  global client_id, mqtt_server
  client = MQTTClient(client_id, mqtt_server)
  #client = MQTTClient(client_id, mqtt_server, user=your_username, password=your_password)
  client.connect()
  print('Connected to %s MQTT broker' % (mqtt_server))
  return client

def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  time.sleep(10)
  machine.reset()

def read_sensor():
  try:
    sensor.measure()
    temp = sensor.temperature()
    # uncomment for Fahrenheit
    #temp = temp * (9/5) + 32.0
    hum = sensor.humidity()
    if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum, int)):
      temp = (b'{0:3.1f},'.format(temp))
      hum =  (b'{0:3.1f},'.format(hum))
      return temp, hum
    else:
      return('Invalid sensor readings.')
  except OSError as e:
    return('Failed to read sensor.')

try:
  client = connect_mqtt()
except OSError as e:
  restart_and_reconnect()

while True:
  try:
    if (time.time() - last_message) > message_interval:
      temp, hum = read_sensor()
      print(temp)
      print(hum)
      client.publish(topic_pub_temp, temp)
      client.publish(topic_pub_hum, hum)
      last_message = time.time()
  except OSError as e:
    restart_and_reconnect()

View raw code

How the Code Works

Import the following libraries:

import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
from machine import Pin
import dht
esp.osdebug(None)
import gc
gc.collect()

In the following variables, you need to enter your network credentials and your broker IP address.

ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'

For example, our broker IP address is: 192.168.1.106.

mqtt_server = '192.168.1.106'

Note: read this tutorial to see how to get your broker IP address.

To create an MQTT client, we need to get the ESP unique ID. That’s what we do in the following line (it is saved on the client_id variable).

client_id = ubinascii.hexlify(machine.unique_id())

Next, create the topics you want your ESP to be publishing in. In our example, it will publish temperature on the esp/dht/temperature topic and humidity on the esp/dht/humidity topic.

topic_pub_temp = b'esp/dht/temperature'
topic_pub_hum = b'esp/dht/humidity'

Then, create the following variables:

last_message = 0
message_interval = 5

The last_message variable will hold the last time a message was sent. The message_interval is the time between each message sent. Here, we’re setting it to 5 seconds (this means a new message will be sent every 5 seconds). You can change it, if you want.

After that, connect the ESP to your local network.

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

print('Connection successful')

Initialize the DHT sensor by creating a dht instance on GPIO 4 as follows:

sensor = dht.DHT22(Pin(4))

If you’re using a DHT11 sensor, uncomment the next line, and comment the previous one:

sensor = dht.DHT11(Pin(4))

Connect to MQTT Broker

The connect_mqtt() function creates an MQTT Client and connects to your broker.

def connect_mqtt():
  global client_id, mqtt_server
  client = MQTTClient(client_id, mqtt_server)
  #client = MQTTClient(client_id, mqtt_server, user=your_username, password=your_password)
  client.connect()
  print('Connected to %s MQTT broker' % (mqtt_server))
  return client

If your MQTT broker requires username and password, you should use the following line to pass your broker username and password as arguments.

client = MQTTClient(client_id, mqtt_server, user=your_username, password=your_password)

Restart and Reconnect

The restart_and_reconnect() function resets the ESP32/ESP8266 board. This function will be called if we’re not able to publish the readings via MQTT in case the broker disconnects.

def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  time.sleep(10)
  machine.reset()

Read DHT Sensor

We created a function called read_sensor() that returns the current temperature and humidity from the DHT sensor and handles any exceptions, in case we’re not able to get readings from the sensor.

def read_sensor():
  try:
    sensor.measure()
    temp = sensor.temperature()
    hum = sensor.humidity()
    if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum, int)):
      temp = (b'{0:3.1f},'.format(temp))
      hum =  (b'{0:3.1f},'.format(hum))

      # uncomment for Fahrenheit
      #temp = temp * (9/5) + 32.0
      return temp, hum
    else:
      return('Invalid sensor readings.')
  except OSError as e:
    return('Failed to read sensor.')

Publishing MQTT Messages

In the while loop, we publish new temperature and humidity readings every 5 seconds.

First, we check if it is time to get new readings:

if (time.time() - last_message) > message_interval:

If it is, request new readings from the DHT sensor by calling the read_sensor() function. The temperature is saved on the temp variable and the humidity is saved on the hum variable.

temp, hum = read_sensor()

Finally, publish the readings by using the publish() method on the client object. The publish() method accepts as arguments the topic and the message, as follows:

client.publish(topic_pub_temp, temp)
client.publish(topic_pub_hum, hum)

Finally, update the time when the last message was sent:

last_message = time.time()

In case the ESP32 or ESP8266 disconnects from the broker, and we’re not able to publish the readings, call the restart_and_reconnect() function to reset the ESP board and try to reconnect to the broker.

except OSError as e:
  restart_and_reconnect()

After uploading the code, you should get new sensor readings on the shell every 5 seconds.

Now, go to the next section to prepare Node-RED to receive the readings the ESP is publishing.

Preparing Node-RED Dashboard

The ESP32 or ESP8266 is publishing temperature readings every 5 seconds on the esp/dht/temperature and esp/dht/humidity 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.

As an example, we’ll create a simple flow using Node-RED to subscribe to those topics and display the readings on gauges.

If you don’t have Node-RED installed, follow the next tutorials:

Having Node-RED running on your Raspberry Pi, go to your Raspberry Pi IP address followed by :1880.

http://raspberry-pi-ip-address:1880

The Node-RED interface should open. Drag two MQTT in nodes, and two gauge nodes to the flow.

ESP32 DHT11 DHT22 Arduino IDE

Click the MQTT node and edit its properties.

MQTT In Node ESP32 ESP8266 Publish Temperature Humidity Node-RED Flow

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’re using a Cloud MQTT broker, you should change that field.

Insert the topic you want to be subscribed to and the QoS. This previous MQTT node is subscribed to the esp/dht/temperature topic.

Click on the other MQTT in node and edit its properties with the same server, but for the other topic: esp/dht/humidity.

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.

ESP32 Gauge Temperature Humidity Node-RED Flow

Wire your nodes as shown below:

ESP32 ESP8266 MQTT Publish DHT Temperature Humidity Node RED Flow

Finally, deploy your flow (press the button on the upper right corner).

Deploy Node-RED button

Alternatively, you can go to Menu > Import and copy the following to your Clipboard to create your Node-RED flow.

[{"id":"59f95d85.b6f0b4","type":"mqtt in","z":"b01416d3.f69f38","name":"","topic":"esp/dht/temperature","qos":"1","datatype":"auto","broker":"8db3fac0.99dd48","x":910,"y":340,"wires":[["2babfd19.559212"]]},{"id":"2babfd19.559212","type":"ui_gauge","z":"b01416d3.f69f38","name":"","group":"37de8fe8.46846","order":2,"width":0,"height":0,"gtype":"gage","title":"Temperature","label":"ºC","format":"{{value}}","min":0,"max":"40","colors":["#00b500","#f7df09","#ca3838"],"seg1":"","seg2":"","x":1210,"y":340,"wires":[]},{"id":"b9aa2398.37ca3","type":"mqtt in","z":"b01416d3.f69f38","name":"","topic":"esp/dht/humidity","qos":"1","datatype":"auto","broker":"8db3fac0.99dd48","x":900,"y":420,"wires":[["d0f75e86.1c9ae"]]},{"id":"d0f75e86.1c9ae","type":"ui_gauge","z":"b01416d3.f69f38","name":"","group":"37de8fe8.46846","order":2,"width":0,"height":0,"gtype":"gage","title":"Humidity","label":"%","format":"{{value}}","min":"30","max":"100","colors":["#53a4e6","#1d78a9","#4e38c9"],"seg1":"","seg2":"","x":1200,"y":420,"wires":[]},{"id":"8db3fac0.99dd48","type":"mqtt-broker","z":"","name":"","broker":"localhost","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"37de8fe8.46846","type":"ui_group","z":"","name":"BME280","tab":"53b8c8f9.cfbe48","order":1,"disp":true,"width":"6","collapse":false},{"id":"53b8c8f9.cfbe48","type":"ui_tab","z":"","name":"Home","icon":"dashboard","order":2,"disabled":false,"hidden":false}]

View raw code

Demonstration

Go to your Raspberry Pi IP address followed by :1880/ui.

http://raspberry-pi-ip-address:1880/ui

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.

ESP32 ESP8266 MQTT Publish Temperature Humidity DHT11 DHT22 Node-RED Dashboard

That’s it! You have your ESP32 or ESP8266 boards publishing DHT temperature and humidity readings to Node-RED via MQTT using MicroPython.

Wrapping Up

MQTT is a great communication protocol to exchange small amounts of data between IoT devices. In this tutorial you’ve 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.

Instead of a DHT11 or DHT22 sensor, you can use any other sensor like a DS18B20 temperature sensor or BME280 sensor.

We have other projects/tutorials related with the DHT sensor that you may also like:

Learn more about MicroPython with our eBook: MicroPython Programming using ESP32/ESP8266.


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

1 thought on “MicroPython: MQTT – Publish DHT11/DHT22 Sensor Readings (ESP32/ESP8266)”

Leave a Comment

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.