ESP32 MQTT – Publish BME280 Sensor Readings (Arduino IDE)

Содержание

Learn how to publish BME280 sensor readings (temperature, humidity and pressure) via MQTT with the ESP32 to any platform that supports MQTT or any MQTT client. As an example, we’ll publish sensor readings to Node-RED Dashboard and the ESP32 will be programmed using Arduino IDE.

ESP32 MQTT Publish BME280 Sensor Readings Arduino IDE

Recommended reading: What is MQTT and How It Works

Project Overview

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

BME280 Publish Readings Node-Red MQTT How it works and project overview

  • The ESP32 requests temperature readings from the BME280 sensor.
  • The temperature readings are published in the esp32/bme280/temperature topic;
  • Humidity readings are published in the esp32/bme280/humiditytopic;
  • Pressure readings are published in the esp32/bme280/pressure topic;
  • Node-RED is subscribed 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 proceeding with this tutorial, make sure you check the following prerequisites.

Arduino IDE

We’ll program the ESP32 using Arduino IDE, so make sure you have the ESP32 add-on installed.

MQTT Broker

Installing Mosquitto MQTT broker Raspberry Pi

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.

You can use any other MQTT broker, including a cloud MQTT broker. We’ll show you how to do that in the code later on.

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

MQTT Libraries

To use MQTT with the ESP32 we’ll use the Async MQTT Client Library.

Installing the Async MQTT Client Library

    . You should have a .zip folder in your Downloads folder

  1. Unzip the .zip folder and you should get async-mqtt-client-master folder
  2. Rename your folder from async-mqtt-client-master to async_mqtt_client
  3. Move the async_mqtt_client folder to your Arduino IDE installation libraries folder
  4. Finally, re-open your Arduino IDE

Alternatively, you can go to Sketch Include Library Add . ZIP library and select the library you’ve just downloaded.

Installing the Async TCP Library

To use MQTT with the ESP, you also need the Async TCP library.

    . You should have a .zip folder in your Downloads folder

  1. Unzip the .zip folder and you should get AsyncTCP-master folder
  2. Rename your folder from AsyncTCP-master to AsyncTCP
  3. Move the AsyncTCP folder to your Arduino IDE installation libraries folder
  4. Finally, re-open your Arduino IDE

Alternatively, you can go to Sketch Include Library Add . ZIP library and select the library you’ve just downloaded.

BME280 Sensor Libraries

To get readings from the BME280 sensor module, we’ll use the Adafruit_BME280 library. You also need to install the Adafruit_Sensor library. Follow the next steps to install the libraries in your Arduino IDE:

1. Open your Arduino IDE and go to Sketch Include Library Manage Libraries. The Library Manager should open.

2. Search for “adafruit bme280 ” on the Search box and install the library.

Installing BME280 library in Arduino IDE

To use the BME280 library, you also need to install the Adafruit Unified Sensor. Follow the next steps to install the library in your Arduino IDE:

3. Search for “Adafruit Unified Sensor“in the search box. Scroll all the way down to find the library and install it.

Installing Adafruit Unified Sensor Driver library

After installing the libraries, restart your Arduino IDE.

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!

Schematic Diagram

Wire the BME280 to the ESP32 as shown in the following schematic diagram with the SDA pin connected to GPIO 21 and the SCL pin connected to GPIO 22 .

ESP32 BME280 Temperature humidity Pressure sensor connected I2C schematic circuit diagram

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.

How the Code Works

The following section imports all the required libraries.

Include your network credentials on the following lines.

Insert the Raspberry Pi IP address, so that the ESP32 connects to your broker.

If you’re using a cloud MQTT broker, insert the broker domain name, for example:

Define the MQTT port.

The temperature, humidity and pressure will be published on the following topics:

Initialize a Adafruit_BME280 object called bme .

The temp , hum and pres variables will hold the temperature, humidity and pressure values from the BME280 sensor.

Create an AsyncMqttClient object called mqttClient to handle the MQTT client and timers to reconnect to your MQTT broker and router when it disconnects.

Then, create some auxiliary timer variables to publish the readings every 10 seconds. You can change the delay time on the interval variable.

MQTT functions: connect to Wi-Fi, connect to MQTT, and Wi-Fi events

We haven’t added any comments to the functions defined in the next code section. Those functions come with the Async Mqtt Client library. The function’s names are pretty self-explanatory.

For example, the connectToWifi() connects your ESP32 to your router:

The connectToMqtt() connects your ESP32 to your MQTT broker:

The WiFiEvent() 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.

The onMqttConnect() function runs after starting a session with the broker.

MQTT functions: disconnect and publish

If the ESP32 loses connection with the MQTT broker, it calls the onMqttDisconnect function that prints that message in the serial monitor.

When you publish a message to an MQTT topic, the onMqttPublish() function is called. It prints the packet id in the Serial Monitor.

Basically, all these functions that we’ve just mentioned are callback functions. So, they are executed asynchronously.

setup()

Now, let’s proceed to the setup() . Initialize the BME280 sensor.

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.

The following line assigns a callback function, so when the ESP32 connects to your Wi-Fi, it will execute the WiFiEvent() function to print the details described earlier.

Finally, assign all the callbacks 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 onMqttConnect() function, and so on.

Broker Authentication

If your broker requires authentication, uncomment the following line and insert your credentials (username and password).

Finally, connect to Wi-Fi.

In the loop() , you create a timer that will allow you to get new readings from the BME280 sensor and publishing them on the corresponding topic every 10 seconds.

Publishing to topics

To publish the readings on the corresponding MQTT topics, use the next lines:

Basically, use the publish() method on the mqttClient object to publish data on a topic. The publish() method accepts the following arguments, in order:

  • MQTT topic (const char*)
  • QoS (uint8_t): quality of service – it can be 0, 1 or 2
  • retain flag (bool): retain flag
  • payload (const char*) – in this case, the payload corresponds to the sensor reading

The QoS (quality of service) is a way to guarantee that the message is delivered. It can be one of the following levels:

  • 0: the message will be delivered once or not at all. The message is not acknowledged. There is no possibility of duplicated messages;
  • 1: the message will be delivered at least once, but may be delivered more than once;
  • 2: the message is always delivered exactly once;

Uploading the code

With your Raspberry Pi powered on and running the Mosquitto MQTT broker, upload the code to your ESP32.

Open the Serial Monitor at a baud rate of 115200 and you’ll see that the ESP32 starts publishing messages on the topics we’ve defined previously.

ESP32 Publish BME280 Sensor Readings MQTT Serial Monitor

Preparing Node-RED Dashboard

The ESP32 is publishing temperature readings every 10 seconds on the esp32/bme280/temperature, esp32/bme280/humidity, and esp32/bme280/pressure 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.

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

Node-RED Drag 6 Nodes MQTT In nodes and Gauges

Click the MQTT node and edit its properties.

MQTT In Node ESP32 Publish Temperature 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 esp32/bme280/temperature topic.

Click on the other MQTT in nodes and edit its properties with the same server, but for the other topics: esp32/bme280/humidity and esp32/bme280/pressure.

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 nodes for the other readings.

ESP32 Gauge Temperature Node-RED Flow

Wire your nodes as shown below:

ESP32 MQTT Publish Temperature Humidity Pressure Node-RED Flow

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

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

Demonstration

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

You should get access to the current BME280 sensor readings on the Dashboard. You can use other dashboard-type nodes to display the readings on different ways.

ESP32 MQTT Publish Temperature Humidity Pressure Node-RED Dashboard

That’s it! You have your ESP32 board publishing BME280 temperature, humidity and pressure readings to Node-RED via MQTT.

Wrapping Up

MQTT is a great communication protocol to exchange small amounts of data between devices. In this tutorial you’ve learned how to publish temperature, humidity and pressure readings from a BME280 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.

Instead of a BME280 sensor, you can use any other sensor like a DS18B20 temperature sensor (ESP32 MQTT – Publish DS18B20 Temperature Readings).

We hope you’ve found this tutorial useful. If you want to learn more about the ESP32, take a look at our resources:

Thanks for reading.

[eBook] Build Web Servers with ESP32 and ESP8266 (2nd Edition)

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…

oled display esp8266 esp32 micropython

MicroPython: OLED Display with ESP32 and ESP8266

ESP32 MQTT – Publish and Subscribe with Arduino IDE

ESP32 Save Data Permanently using the Preferences Library

ESP32 Save Data Permanently using Preferences Library

Enjoyed this project? Stay updated by subscribing our newsletter!

45 thoughts on “ESP32 MQTT – Publish BME280 Sensor Readings (Arduino IDE)”

Nice tutorial. What is the syntax for subscribing to a topic then reading it? Ei: topic ‘command’ for an on off button on node red to control an LED with the ESP32?

Nice project. But it seems someting is missing about freertos/*.h

What do you mean? do you get an error when compiling? Did you check all the required libraries?
Thanks!

There is no reference to how to install freertos in your tutorial, Rui.

Are you using the latest ESP32 board add-on in your Arduino IDE? I think I’ve never had to install that library and it’s installed by default

Same. using an 8266, don’t have it, don’t see it, don’t see a match. see close, but lots of close. stuck there.

Hi.
I never need to install that.
Never had that problem.
Make sure you have the latest version of the ESP8266 boards and Arduino IDE.
Regards,
Sara

Excelente tutorial y cubre casi todos los temas en los que estoy trabajando. Muchas gracias.
Solo me falta aún aclarar el tema inverso: por ejemplo controlar un rele desde el Dashboard. Tienen alguna indicación que puedan compartir, al respecto?

Hi.
We have this tutorial that shows how to control an LED from the dashboard: https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/
However, it uses a different library.
Regards,
Sara

Great tutorial!
It would even greater if instead of using wifi for transport, lora (non-TTN) was used to push to Node Red. Maybe a future tutorial?

At the moment we don’t have any tutorials on that subject, I still think the most reliable method is using MQTT in your network. But we’ll explore other methods to communicate to Node-RED

Thank you for the excellent tutorial!
Is it possible to adopt this project example on ESP8266 Boar?

Yes, we’ll be publishing the ESP8266 version in the upcoming weeks.

Excellent Helps us with this project for the ESP8266.
Thank you

Byron Morgan has posted a contribution which says that the ‘freertos problem’ also appears when using an ESP8266 board. It seems that you are going to publish an ESP8266 version of the ESP32 guide. Will this address the ‘freertos problem’ that has been reported in several posts?

Thanks in advance

Hi.
We’ve never had that problem using the ESP32 or ESP8266. So, I don’t know what might be causing the issue.
We have a similar guide for the ESP8266 if you want to follow: https://randomnerdtutorials.com/esp8266-nodemcu-mqtt-publish-bme280-arduino/
Note that the ESP8266 uses the ESPAsync TCP Library instead of the AsyncTCP.
Regards,
Sara

Nice tutorial, it helped me developing a dashboard of myself.
But I have a question: how to set the order of the gauges e.g. which one comes at the top and which one at the bottom?
The order in the editor seems to have no influence.

You need to open the Dashboard menu, then the Tab where your gauges are located and you can drag the gauge to move them:
https://randomnerdtutorials.com/wp-content/uploads/2020/04/move-gauge-node-red.png
Then, click the Deploy button for change to take effect.

In Node-red I can’t find the “UI_gauge” node, it’s not in the installation list either

I just modified some line in order to access DNS server and get mqttdashboard MQTT server.
The code connects perfectly to Wifi and Mqtt server, it publish the topics, but I can not see topics updated using MQTT.fx. With previous application I used (it was blocking, therefore I changed to Yours) worked.
I also noticed, that I dont get confirmation of publishing, as described in the web page, but only line by line
Publishing on topics esp32/vojko/pressure or other topics used, but without Publish Aknowledged.

MQTT seems to be connected since there is no reconnection attempts.

Can You please help me a little, to start up with MQTT on ESP32?

Thanks a lot,
Vojko

Hi.
That means that your messages are being published successfully. But are not being received, otherwise you should be receiving an acknowledge message.
Double-check that your Node-RED is subscribed to the same topics the ESP32 is publishing in. You might also need to restart your Raspberry Pi or Node-RED.
Regards,
Sara

Buenas noches. Excelente tutorial. Tengo un problema al compilar, me aparece el mensaje:

freertos/FreeRTOS.h: No such file or directory

Porfavor podrian ayudarme

Hi.
Double-check that you have selected the right board in “Tools Board”.
This code is compatible with ESP32 boards.
Regards,
Sara

Hi. I had a problem: “Attempting MQTT connection…failed, rc=-2 try again in 5 seconds”. At the end of ‘void reconnect() <‘ I addes a call to ‘setup_wifi()’ if the connection failed more than 15 times – Just for testing.

Hi,
for me worker this example really fine.
Some my experiences here:
you can check your MQTT broker connection with a client from your handy (iOS – MQTTool, Android – MyMQTT) or from your laptop (MQTTBox).
If you are using a MQTT broker on the same laptop where your client is running it is a good idea to check the connection from another device too.
I’m successfully using the host mqtt.eclipse.org (for MQTTBox: protocol mqtt/tcp, “Broker is MQTT v.3.1.1compliant – yes”) as the public broker for my tests. The ESP Projekt worked with this broker fine too.
I hope this can help.
Regards,
Volodymyr

Thanks for your reply. Seems like you don’t understand my comment.
If you loose the WiFi connection you also loose your MQTT-connection. The program will never reconnect, because you only try to reconnect MQTT-connection – never the WiFi connection

The WiFiEvent() callback function provides two activities:
– the WIFI reconnection for the SYSTEM_EVENT_STA_DISCONNECTED event,
– the MQTT reconnection for the SYSTEM_EVENT_STA_GOT_IP event.
It seems me to be the same as in your project.

After the board was started and the MQTT connection was established I have plugged my WIFI router off and in few seconds plugged it on. The WIFI connection and MQTT connection was successfully re-established. Here are my serial monitor messages:


Publish received.
topic: /$_abra$$cadabra/Nö/Heizung/2
qos: 2
dup: 0
retain: 0
len: 6
index: 0
total: 6
Publish acknowledged.
packetId: 3
Disconnected from MQTT.
[WiFi-event] event: 5
WiFi lost connection
Connecting to Wi-Fi…
[WiFi-event] event: 5
WiFi lost connection
Connecting to Wi-Fi…

[WiFi-event] event: 5
WiFi lost connection
Connecting to Wi-Fi…
[WiFi-event] event: 4
[WiFi-event] event: 7
WiFi connected
IP address:
192.168.2.105
Connecting to MQTT…
Connected to MQTT.
Session present: 0
Subscribing at QoS 2, packetId: 1
Publishing at QoS 0
Publishing at QoS 1, packetId: 2
Publishing at QoS 2, packetId: 3
Subscribe acknowledged.
packetId: 1
qos: 2
Publish received.
topic: /$_abra$$cadabra/Nö/Temperature/2
qos: 1
dup: 0
retain: 1
len: 5
index: 0
total: 5

Du you see some differences in these two projects?

The project You are referring to, is completely different from the one from Rui Santos, which I am talking about. I just tried to point out that the reconnection to WiFi is missing in Rui’s project. So this will be ‘the never ending story’.

Hi,
I have implemented this project with my DOIT ESP32 DEVKIT V1 board and with a BME/BMP280 sensor. the source code is the same as on this website; only SSID, password and MQTT broker data are changed.
I have the same results as above: after the board was started and the MQTT connection was established I have plugged my WIFI router off and in few seconds plugged it on. The WIFI connection and MQTT connection was successfully re-established.
Regards,
Volodymyr

P.S. My serial monitor messages:

Publishing on topic esp32/bme280/temperature at QoS 1, packetId: 226Message: 28.35
Publishing on topic esp32/bme280/humidity at QoS 1, packetId 227: Message: 28.87
Publishing on topic esp32/bme280/pressure at QoS 1, packetId: 228Message: 963.139
Publish acknowledged. packetId: 226
Publish acknowledged. packetId: 227
Publish acknowledged. packetId: 228
Publishing on topic esp32/bme280/temperature at QoS 1, packetId: 229Message: 28.35
Publishing on topic esp32/bme280/humidity at QoS 1, packetId 230: Message: 28.89
Publishing on topic esp32/bme280/pressure at QoS 1, packetId: 231Message: 963.150
Publish acknowledged. packetId: 229
Publish acknowledged. packetId: 230
Publish acknowledged. packetId: 231
Disconnected from MQTT.
[WiFi-event] event: 5
WiFi lost connection
Publishing on topic esp32/bme280/temperature at QoS 1, packetId: 0Message: 28.34
Publishing on topic esp32/bme280/humidity at QoS 1, packetId 0: Message: 28.87
Publishing on topic esp32/bme280/pressure at QoS 1, packetId: 0Message: 963.160
Connecting to Wi-Fi…
[WiFi-event] event: 5
WiFi lost connection
Connecting to Wi-Fi…
[WiFi-event] event: 5
WiFi lost connection
Connecting to Wi-Fi…

[WiFi-event] event: 5
WiFi lost connection
Connecting to Wi-Fi…
[WiFi-event] event: 5
WiFi lost connection
Connecting to Wi-Fi…
[WiFi-event] event: 4
[WiFi-event] event: 7
WiFi connected
IP address:
192.168.2.105
Connecting to MQTT…
Connected to MQTT.
Session present: 0
Publishing on topic esp32/bme280/temperature at QoS 1, packetId: 1Message: 28.52
Publishing on topic esp32/bme280/humidity at QoS 1, packetId 2: Message: 28.73
Publishing on topic esp32/bme280/pressure at QoS 1, packetId: 3Message: 963.148
Publish acknowledged. packetId: 1
Publish acknowledged. packetId: 2
Publish acknowledged. packetId: 3
Publishing on topic esp32/bme280/temperature at QoS 1, packetId: 4Message: 28.49
Publishing on topic esp32/bme280/humidity at QoS 1, packetId 5: Message: 28.73
Publishing on topic esp32/bme280/pressure at QoS 1, packetId: 6Message: 963.187


Источник: randomnerdtutorials.com