Simple MQTT temperature sensor

In the previous post about monitoring temperature we have used a simple RS-485 connection to communicate with a sensor. While this approach is very simple and has been proven to work well in many applications it can be complicated when the amount of connected sensors increases. Also adding or removing sensors can cause complications.

Modern technologies allow us to connect sensors using existing computer networks. For example the incredible ESP32 SoC can easily be programmed to read data from a sensor and relay them over WiFi using MQTT protocol.

MQTT protocol is a publish-subscribe protocol that works over TCP/IP connections. One or more clients are connecting to a single broker and exchanging information with it. In the most simple case one client sends data to the broker – publishes in a given topic. Anyone who connects to this broker and subscribes to the topic gets notified when new data arrive.

This example uses the DHT22 temperature+humidity sensor and ESP-WROOM-32 development kit working as a client. The broker is a PC running Ubuntu 18.04. Both devices are connected to the same WiFi network.

First it’s necessary to install the Mosquitto broker.

sudo apt install mosquitto mosquitto-clients

Now the broker should be installed, up and running. The default configuration does not use any encryption or password protection, which is fine for testing purposes. The functionality can be tested by subscribing to a topic and publishing a message to it.

Connecting the DHT22 sensor to ESP32 is simple. It can be powered from the 3.3V power supply. The sensor’s data output pin can be connected straight to one of ESP32’s digital inputs with approximately 4k7 kΩ pull-up resistor.

The ESP32 has to run a program that connects to WiFi, connects to the MQTT broker, reads new values from the sensor and periodically sends it over to the broker. This relatively complex functionality can be easily achieved using Arduino libraries. There is already a very good example on how to achieve this. Or you can use the final program used in this example.

Now if everything goes as expected the ESP32 should boot up, connect to the broker and start sending measured values periodically.

After subscribing to the topic the broker makes all new measurements available.

2 thoughts on “Simple MQTT temperature sensor”

  1. Hi, nice tutorial. I downloaded the program but when I try to compile, I get this error:

    Compilation error: ‘TaskHandle_t’ does not name a type

    How can I solve the issue?
    Thank you.

    1. I can’t try that out but looks like a header include is missing in the example. Try adding (one of) these:

      #include “freertos/FreeRTOS.h”
      #include “freertos/task.h”

Leave a Reply

Your email address will not be published. Required fields are marked *