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

  1. Click here to download the Async MQTT client library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get async-mqtt-client-master folder
  3. Rename your folder from async-mqtt-client-master to async_mqtt_client
  4. Move the async_mqtt_client folder to your Arduino IDE installation libraries folder
  5. 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.

  1. Click here to download the Async TCP client library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get AsyncTCP-master folder
  3. Rename your folder from AsyncTCP-master to AsyncTCP
  4. Move the AsyncTCP folder to your Arduino IDE installation libraries folder
  5. 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.

To learn more about the BME280 sensor, read our guide: ESP32 with BME280 Sensor using Arduino IDE (Pressure, Temperature, Humidity).

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

Code

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.

/*
  Rui Santos & Sara Santos - Random Nerd Tutorials
  Complete project details at https://RandomNerdTutorials.com/esp32-mqtt-publish-bme280-arduino/
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <WiFi.h>
extern "C" {
  #include "freertos/FreeRTOS.h"
  #include "freertos/timers.h"
}
#include <AsyncMqttClient.h>

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

// Raspberry Pi Mosquitto MQTT Broker
#define MQTT_HOST IPAddress(192, 168, 1, XXX)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST "example.com"
#define MQTT_PORT 1883

// Temperature MQTT Topics
#define MQTT_PUB_TEMP "esp32/bme280/temperature"
#define MQTT_PUB_HUM "esp32/bme280/humidity"
#define MQTT_PUB_PRES "esp32/bme280/pressure"

// BME280 I2C
Adafruit_BME280 bme;
// Variables to hold sensor readings
float temp;
float hum;
float pres;

AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;

unsigned long previousMillis = 0;   // Stores last time temperature was published
const long interval = 10000;        // Interval at which to publish sensor readings

void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

void connectToMqtt() {
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
  switch(event) {
    case ARDUINO_EVENT_WIFI_STA_GOT_IP:
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      connectToMqtt();
      break;
    case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
      xTimerStart(wifiReconnectTimer, 0);
      break;
  }
}

void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");
  if (WiFi.isConnected()) {
    xTimerStart(mqttReconnectTimer, 0);
  }
}

/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.println("Subscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
  Serial.print("  qos: ");
  Serial.println(qos);
}
void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}*/

void onMqttPublish(uint16_t packetId) {
  Serial.print("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void setup() {
  Serial.begin(115200);
  Serial.println();
  
  // Initialize BME280 sensor 
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
  
  mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

  WiFi.onEvent(WiFiEvent);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  //mqttClient.onSubscribe(onMqttSubscribe);
  //mqttClient.onUnsubscribe(onMqttUnsubscribe);
  mqttClient.onPublish(onMqttPublish);
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  // If your broker requires authentication (username and password), set them below
  //mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");
  connectToWifi();
}

void loop() {
  unsigned long currentMillis = millis();
  // Every X number of seconds (interval = 10 seconds) 
  // it publishes a new MQTT message
  if (currentMillis - previousMillis >= interval) {
    // Save the last time a new reading was published
    previousMillis = currentMillis;
    // New BME280 sensor readings
    temp = bme.readTemperature();
    //temp = 1.8*bme.readTemperature() + 32;
    hum = bme.readHumidity();
    pres = bme.readPressure()/100.0F;
    
    // Publish an MQTT message on topic esp32/BME2800/temperature
    uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());                            
    Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", MQTT_PUB_TEMP, packetIdPub1);
    Serial.printf("Message: %.2f \n", temp);

    // Publish an MQTT message on topic esp32/BME2800/humidity
    uint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());                            
    Serial.printf("Publishing on topic %s at QoS 1, packetId %i: ", MQTT_PUB_HUM, packetIdPub2);
    Serial.printf("Message: %.2f \n", hum);

    // Publish an MQTT message on topic esp32/BME2800/pressure
    uint16_t packetIdPub3 = mqttClient.publish(MQTT_PUB_PRES, 1, true, String(pres).c_str());                            
    Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", MQTT_PUB_PRES, packetIdPub3);
    Serial.printf("Message: %.3f \n", pres);
  }
}

View raw code

How the Code Works

The following section imports all the required libraries.

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <WiFi.h>
extern "C" {
  #include "freertos/FreeRTOS.h"
  #include "freertos/timers.h"
}
#include <AsyncMqttClient.h>

Include your network credentials on the following lines.

#define WIFI_SSID "REPLACE_WITH_YOUR_SSID"
#define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD"

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

#define MQTT_HOST IPAddress(192, 168, 1, 106)

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

#define MQTT_HOST "example.com"

Define the MQTT port.

#define MQTT_PORT 1883

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

#define MQTT_PUB_TEMP "esp32/bme280/temperature"
#define MQTT_PUB_HUM  "esp32/bme280/humidity"
#define MQTT_PUB_PRES "esp32/bme280/pressure"

Initialize a Adafruit_BME280 object called bme.

Adafruit_BME280 bme;

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

float temp;
float hum;
float pres;

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

AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;

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

unsigned long previousMillis = 0;  // Stores last time temperature was published
const long interval = 10000;       // Interval at which to publish sensor readings

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:

void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

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

void connectToMqtt() {
  Serial.println("Connecting to MQTT…");
  mqttClient.connect();
 }

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.

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
  switch(event) {
    case ARDUINO_EVENT_WIFI_STA_GOT_IP:
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      connectToMqtt();
      break;
    case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      xTimerStop(mqttReconnectTimer, 0);
      xTimerStart(wifiReconnectTimer, 0);
      break;
  }
}

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

void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);
}

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.

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");
  if (WiFi.isConnected()) { 
    xTimerStart(mqttReconnectTimer, 0);
  }
}

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

void onMqttPublish(uint16_t packetId) {
  Serial.println("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

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.

if (!bme.begin(0x76)) {
  Serial.println("Could not find a valid BME280 sensor, check wiring!");
  while (1);
}

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.

mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

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.

WiFi.onEvent(WiFiEvent);

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.

mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
//mqttClient.onSubscribe(onMqttSubscribe);
//mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);

Broker Authentication

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

mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");

Finally, connect to Wi-Fi.

connectToWifi();

loop()

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.

unsigned long currentMillis = millis();
// Every X number of seconds (interval = 10 seconds) 
// it publishes a new MQTT message
if (currentMillis - previousMillis >= interval) {
  // Save the last time a new reading was published
  previousMillis = currentMillis;
  // New BME280 sensor readings
  temp = bme.readTemperature();
  //temp = 1.8*bme.readTemperature() + 32;
  hum = bme.readHumidity();
  pres = bme.readPressure()/100.0F;

Learn more about getting readings from the BME280 sensor: ESP32 with BME280 Temperature, Humidity and Pressure Sensor Guide.

Publishing to topics

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

uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());
uint16_t packetIdPub2 = mqttClient.publish(MQTT_PUB_HUM, 1, true, String(hum).c_str());
uint16_t packetIdPub3 = mqttClient.publish(MQTT_PUB_PRES, 1, true, String(pres).c_str());

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;
  • Learn about MQTT QoS.

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.

http://raspberry-pi-ip-address: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).

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":"5a45b8da.52b0d8","type":"mqtt in","z":"b01416d3.f69f38","name":"","topic":"esp32/bme280/temperature","qos":"1","datatype":"auto","broker":"8db3fac0.99dd48","x":340,"y":120,"wires":[["3042e15e.80a4ee"]]},{"id":"3042e15e.80a4ee","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":610,"y":120,"wires":[]},{"id":"8ff168f0.0c74a8","type":"mqtt in","z":"b01416d3.f69f38","name":"","topic":"esp32/bme280/humidity","qos":"1","datatype":"auto","broker":"8db3fac0.99dd48","x":320,"y":200,"wires":[["29251f29.6687c"]]},{"id":"29251f29.6687c","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":600,"y":200,"wires":[]},{"id":"681a1588.8506fc","type":"mqtt in","z":"b01416d3.f69f38","name":"","topic":"esp32/bme280/pressure","qos":"1","datatype":"auto","broker":"8db3fac0.99dd48","x":330,"y":280,"wires":[["41164c6.e7b3cb4"]]},{"id":"41164c6.e7b3cb4","type":"ui_gauge","z":"b01416d3.f69f38","name":"","group":"37de8fe8.46846","order":2,"width":0,"height":0,"gtype":"gage","title":"Pressure","label":"hPa","format":"{{value}}","min":"900","max":"1100","colors":["#a346ff","#bd45cb","#7d007d"],"seg1":"","seg2":"","x":600,"y":280,"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 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.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

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

  1. Hi,

    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?

    Thanks,
    Joe

    Reply
          • I had alreeady installed a ESP32 driver in my Arduino IDE. When I compiled the Code the first time, I had the same error message. Then I read “Installing ESP32 in Arduino IDE” und installed exactly in this way. This solves the problem and I can compile without errors.

    • 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.

      Reply
      • 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

        Reply
  2. 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?

    Reply
  3. 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?

    Reply
    • 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

      Reply
  4. 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.

    Reply
  5. Dear Rui,

    I use Your code for ESP32 MQTT example from
    https://randomnerdtutorials.com/esp32-mqtt-publish-bme280-arduino/

    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

    Reply
    • 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

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

    freertos/FreeRTOS.h: No such file or directory

    #include “freertos/FreeRTOS.h”

    Porfavor podrian ayudarme

    Muchas gracias

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

      Reply
  7. 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.

    Reply
    • 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

      Reply
      • 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

        Reply
        • Hi,

          I have checked now a project example from https://github.com/marvinroger/async-mqtt-client/tree/master/examples/FullyFeatured-ESP32 on my board DOIT ESP32 DEVKIT V1

          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?

          Regards,
          Volodymyr

          Reply
          • 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

  8. Fails on
    #include “freertos/freertos.h”
    #include “freertos/timers.h”

    files not found. Where do these come from?

    Reply
  9. Wonderful and thorough, however even with all the proper setup and tested active MQTT, I see no incoming messages (debug nodes attached in Node Red). I have used MQTTBox to verify that MQTT is set up and Node Red can read/display information sent from MQTTBox, but not from this project. Also verified that I am connected to the MQTT listener in my Pi with a simple MQTT project.

    Output from Code (simplified for testing) = Publishing on topic esp/bme280/temperature at QoS 1, packetId: 0 Message: 80.78

    Any help much appreciated!

    Reply
  10. Had that problem when i forgot to choose the correct board (i had chosen arduino Uno …)
    after selecting the correct board (mine was “ESP32 Dev Module”) it worked imidiately, no more problem with the FreeRTOS.

    Hope that works for you ^^

    Reply
  11. i don’t know what to do, i get out that connects and disconnects from the broker and only send the data once it is no longer sent to the dash board, and in the raspberry net broker says that the broker is fine, not that i can do now for what functions
    this publish the arduino serial:
    Connecting to MQTT…
    Disconnected from MQTT.
    Connecting to MQTT…
    Disconnected from MQTT.
    Publishing on topic esp32/bme280/temperature at QoS 1, packetId: 0Message: 20.10
    Publishing on topic esp32/bme280/humidity at QoS 1, packetId 0: Message: 85.00
    Publishing on topic esp32/bme280/pressure at QoS 1, packetId: 0Message: 50.300
    Connecting to MQTT…
    Disconnected from MQTT.

    Reply
  12. Great experience with this project. I got everything to work including the Node Red Dashboard. I want to port this over to a Python app on a raspberry pi 4. I had working (but unreliable) ESP8266 code using DHT22 sensor. I am having trouble trying to convert this existing code to work with your ESP32 code. I would like to populate three labels in my python code (using tkiner gui) with the published code of temperature, humidity and pressure from the ESP32 MQTT code. My raspberry pi is the broker for this application. I have tested the connection using MQTT Explorer and all is well there. Thanks

    Reply
  13. Nice tutorial, thank you very much.
    If you want to use a free broker in the cloud, is there a way to access the Dashboard with a link similar to http://raspberry-pi-ip-address:1880/ui as when we tested it locally? For example, I already have the same bme280 sensor working in broker.hivemq.com but I don’t know how to access its Dashboard from any browser, and to have the possibility to share the link(url) to another person to monitoring.

    Reply
  14. Hey,

    thank you for the great tutorial.

    I dont want to use the node red and the Raspberry Pi.

    My Applecation:
    Sensor to ESP32 (via I²C)
    The ESP32 is connected to a router local wifi (without internet)
    The PC is connected to the router via Ethernet
    I have installed mosquitto broker and MQTT Explorer as a Mqtt Client instead of red node.

    But its not working for mr

    Reply
  15. I like to put my projects in a 3d printed case. Is there a way to isolate the temperature sensor from the heat of the esp32? I have put vents in the case and mounted the sensor on the outside of the case. I still get elevated temperature readings.

    Anyway I can post a picture?

    Any suggestions would be helpful.

    Reply
  16. Great tutorial.
    When trying to compile the code, copied from the tutorial, I get pages of errors similar to:
    “c:/users/john/appdata/local/arduino15/packages/esp32/tools/xtensa-esp32-elf-gcc/gcc8_4_0-
    esp-2021r2-patch3/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/
    ld.exe:
    C:\Users\John\OneDrive\Documents\Arduino\libraries\AsyncMqttClient\src/AsyncMqttClient.cp
    p:700: undefined reference to `AsyncClient::connect(IPAddress, unsigned short)'”

    My understanding of these error messages suggests I am using the wrong “AsyncMqttClient.h” include file.

    https://github.com › marvinroger › async-mqtt-client
    Jul 27, 2021 · Async MQTT client for ESP8266 and ESP32. An Arduino for ESP8266 and ESP32 asynchronous MQTT client implementation, built on me-no-dev/ESPAsyncTCP (ESP8266) | me-no-dev/AsyncTCP (ESP32).. This is the library package I am using.

    Please point me in the right direction to resolve this issue.

    Reply
  17. Oi, você teria esse mesmo projeto, porém? captando dados de um esp32, enviando por rede lora a outro esp32(Gatwey)? preciso exatamente dessa aplicação, porém a captura de dados precisa ser feita a 1km de distancia.

    Reply
  18. Hello, thank you for the tutorial.

    1.
    In my case, everything else seems to work but while the MQTT broker does get a connection attempt from the esp32, it regards it as an unknown/unauthenticated connection.
    I have added the authentication details into my code and have tested that the broker itself works by following one of your tutorials on it.

    What might be the issue here?

    Where is the Async TCP library exactly used in the code? Should the library be included in the beginning of the code (“#include “AsyncTCP.h”)?

    Reply
  19. Hi there! A great tutorial, thus a good learning experience for sure. A couple of items to note. As I am using an esp32S3, the library I needed to use was AsyncMQTT_ESP32.h rather than that specified in the code example (AsyncMqttClient.h). That said, I got it to work quite well thus far.
    I also wanted to note that after installing the mosquitto MQTT broker on my raspberry pi400, that the mosquitto log, db and run directories needed to be moved to an area where the user has write permissions. This required changes to the mosquitto configuration file.
    Lastly, getting ‘node red’ going was a bit of a challenge, but a link to the Node Red documentation was a great find. The link that really helped is : https://nodered.org/docs/user-guide/

    ..rick epstein..

    Reply

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.