ESP32 MQTT – Publish and Subscribe with Arduino IDE

This project shows how to use MQTT communication protocol with the ESP32 to publish messages and subscribe to topics. As an example, we’ll publish BME280 sensor readings to the Node-RED Dashboard, and control an ESP32 output. The ESP32 we’ll be programmed using Arduino IDE.

Project Overview

In this example, there’s a Node-RED application that controls ESP32 outputs and receives sensor readings from the ESP32 using MQTT communication protocol. The Node-RED application is running on a Raspberry Pi.

We’ll use the Mosquitto broker installed on the same Raspberry Pi. The broker is responsible for receiving all messages, filtering the messages, decide who is interested in them and publishing the messages to all subscribed clients.

The following figure shows an overview of what we’re going to do in this tutorial.

  • The Node-RED application publishes messages (“on” or “off“) in the topic esp32/output. The ESP32 is subscribed to that topic. So, it receives the message with “on” or “off” to turn the LED on or off.
  • The ESP32 publishes temperature on the esp32/temperature topic and the humidity on the esp32/humidity topic. The Node-RED application is subscribed to those topics. So, it receives temperature and humidity readings that can be displayed on a chart or gauge, for example.

Note: there’s also a similar tutorial on how to use the ESP8266 and Node-RED with MQTT.

Prerequisites

If you like home automation and you want to learn more about Node-RED, Raspberry Pi, ESP8266 and Arduino, we recommend trying our course: Build a Home Automation System with Node-RED, ESP8266 and Arduino. We also have a course dedicated to the ESP32: Enroll in Learn ESP32 with Arduino IDE course.

Parts Required

These are the parts required to build the circuit (click the links below to find the best price at Maker Advisor):

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!

Introducing the BME280 Sensor Module

The BME280 sensor module reads temperature, humidity, and pressure. Because pressure changes with altitude, you can also estimate altitude. However, in this tutorial we’ll just read temperature and humidity. There are several versions of this sensor module, but we’re using the one shown in the figure below.

The sensor can communicate using either SPI or I2C communication protocols (there are modules of this sensor that just communicate with I2C, these just come with four pins).

To use SPI communication protocol, use the following pins:

  • SCK – this is the SPI Clock pin
  • SDO – MISO
  • SDI – MOSI
  • CS – Chip Select

To use I2C communication protocol, the sensor uses the following pins:

  • SCK – SCL pin
  • SDI – SDA pin

Schematic

We’re going to use I2C communication with the BME280 sensor module. For that, wire the sensor to the ESP32 SDA and SCL pins, as shown in the following schematic diagram.

We’ll also control an ESP32 output, an LED connected to GPIO 4.

Here’s how your circuit should look:

Preparing the Arduino IDE

There’s an add-on for the Arduino IDE that allows you to program the ESP32 using the Arduino IDE and its programming language. Follow one of the next tutorials to prepare your Arduino IDE to work with the ESP32, if you haven’t already.

After making sure you have the ESP32 add-on installed, you can continue with this tutorial.

Installing the PubSubClient Library

The PubSubClient library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT (basically allows your ESP32 to talk with Node-RED).

  1. Click here to download the PubSubClient library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get pubsubclient-master folder
  3. Rename your folder from pubsubclient-master to pubsubclient
  4. Move the pubsubclient folder to your Arduino IDE installation libraries folder
  5. Then, re-open your Arduino IDE

The library comes with a number of example sketches. See File >Examples > PubSubClient within the Arduino IDE software.

Important: PubSubClient is not fully compatible with the ESP32, but the example provided in this tutorial is working very reliably during our tests.

Installing the BME280 library

To take readings from the BME280 sensor module we’ll use the Adafruit_BME280 library. Follow the next steps to install the library in your Arduino IDE:

  1. Click here to download the Adafruit-BME280 library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get Adafruit-BME280-Library-master folder
  3. Rename your folder from Adafruit-BME280-Library-master to Adafruit_BME280_Library
  4. Move the Adafruit_BMPE280_Library folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Alternatively, you can go to Sketch > Include Library > Manage Libraries and type “adafruit bme280” to search for the library. Then, click install.

Installing the Adafruit_Sensor library

To use the BME280 library, you also need to install the Adafruit_Sensor library. Follow the next steps to install the library:

  1. Click here to download the Adafruit_Sensor library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get Adafruit_Sensor-master folder
  3. Rename your folder from Adafruit_Sensor-master to Adafruit_Sensor
  4. Move the Adafruit_Sensor folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Uploading code

Now, you can upload the following code to your ESP32. The code is commented on where you need to make changes. You need to edit the code with your own SSID, password and Raspberry Pi IP address.

/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>

// Replace the next variables with your SSID/Password combination
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "YOUR_MQTT_BROKER_IP_ADDRESS";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

//uncomment the following lines if you're using SPI
/*#include <SPI.h>
#define BME_SCK 18
#define BME_MISO 19
#define BME_MOSI 23
#define BME_CS 5*/

Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
float temperature = 0;
float humidity = 0;

// LED Pin
const int ledPin = 4;

void setup() {
  Serial.begin(115200);
  // default settings
  // (you can also pass in a Wire library object like &Wire2)
  //status = bme.begin();  
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(ledPin, OUTPUT);
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off". 
  // Changes the output state according to the message
  if (String(topic) == "esp32/output") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(ledPin, HIGH);
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(ledPin, LOW);
    }
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("esp32/output");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
    
    // Temperature in Celsius
    temperature = bme.readTemperature();   
    // Uncomment the next line to set temperature in Fahrenheit 
    // (and comment the previous temperature line)
    //temperature = 1.8 * bme.readTemperature() + 32; // Temperature in Fahrenheit
    
    // Convert the value to a char array
    char tempString[8];
    dtostrf(temperature, 1, 2, tempString);
    Serial.print("Temperature: ");
    Serial.println(tempString);
    client.publish("esp32/temperature", tempString);

    humidity = bme.readHumidity();
    
    // Convert the value to a char array
    char humString[8];
    dtostrf(humidity, 1, 2, humString);
    Serial.print("Humidity: ");
    Serial.println(humString);
    client.publish("esp32/humidity", humString);
  }
}

View raw code

This code publishes temperature and humidity readings on the esp32/temperature and esp32/humidity topics trough MQTT protocol.

The ESP32 is subscribed to the esp32/output topic to receive the messages published on that topic by the Node-RED application. Then, accordingly to the received message, it turns the LED on or off.

Subscribing to MQTT topics

In the reconnect() function, you can subscribe to MQTT topics. In this case, the ESP32 is only subscribed to the esp32/output:

client.subscribe("esp32/output");

In the callback() function, the ESP32 receives the MQTT messages of the subscribed topics. According to the MQTT topic and message, it turns the LED on or off:

// If a message is received on the topic esp32/output, you check if the message is either "on" or "off". 
// Changes the output state according to the message
if (String(topic) == "esp32/output") {
  Serial.print("Changing output to ");
  if (messageTemp == "on") {
    Serial.println("on");
    digitalWrite(ledPin, HIGH);
  }
  else if (messageTemp == "off") {
    Serial.println("off");
    digitalWrite(ledPin, LOW);
  }
}

Publishing MQTT messages

In the loop(), new readings are being published every 5 seconds:

if (now - lastMsg > 5000) { ... }

By default the ESP32 is sending the temperature in Celsius, but you can uncomment the last line to send the temperature in Fahrenheit:

// Temperature in Celsius
temperature = bme.readTemperature(); 
// Uncomment the next line to set temperature in Fahrenheit 
// (and comment the previous temperature line)
//temperature = 1.8 * bme.readTemperature() + 32; // Temperature in Fahrenheit

You need to convert the temperature float variable to a char array, so that you can publish the temperature reading in the esp32/temperature topic:

// Convert the value to a char array
char tempString[8];
dtostrf(temperature, 1, 2, tempString);
Serial.print("Temperature: ");
Serial.println(tempString);
client.publish("esp32/temperature", tempString);

The same process is repeated to publish the humidity reading in the esp32/humidity topic:

humidity = bme.readHumidity();
// Convert the value to a char array
char humString[8];
dtostrf(humidity, 1, 2, humString);
Serial.print("Humidity: ");
Serial.println(humString);
client.publish("esp32/humidity", humString);

Creating the Node-RED flow

Before creating the flow, you need to have installed in your Raspberry Pi:

After that, import the Node-RED flow provided. Go to the GitHub repository or click the figure below to see the raw file, and copy the code provided.

Next, in the Node-RED window, at the top right corner, select the menu, and go to Import  > Clipboard.

Then, paste the code provided and click Import.

The following nodes should load:

After making any changes, click the Deploy button to save all the changes.

Node-RED UI

Now, your Node-RED application is ready. To access Node-RED UI and see how your application looks, access any browser in your local network and type:

http://Your_RPi_IP_address:1880/ui

Your application should look as shown in the following figure. You can control the LED on and off with the switch or you can view temperature readings in a chart and the humidity values in a gauge.

Demonstration

Watch the next video for a live demonstration:

Open the Arduino IDE serial monitor to take a look at the MQTT messages being received and published.

Wrapping Up

In summary, we’ve shown you the basic concepts that allow you to turn on lights and monitor sensors with your ESP32 using Node-RED and the MQTT communication protocol. You can use this example to integrate in your own home automation system, control more outputs, or monitor other sensors.

You might also like reading:

We hope you’ve found this tutorial useful.

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!

91 thoughts on “ESP32 MQTT – Publish and Subscribe with Arduino IDE”

  1. After entering Node-RED code the the graph and gauge node show up as unknown, is there some other “Libraries” that have to be installed?

    Reply
  2. Great guide as always!!

    One question though, where is the sensor data stored?

    I assume on the RPi somewhere – maybe in the node.red folder?

    Many thanks!

    Reply
  3. Many thanks – so no data is ‘stored’ for later use, its only kept in the current deployed Node Red instance for the duration of the charts settings e.g. 1 hour?

    Simon

    Reply
  4. Hi Rui & Sara,

    I’ve been following your blog since long time, Here I would like to suggest one thing, If you add “search box” in your website, it’ll be great. Searching for coarses, tutorials will become more easy.
    then.
    Here in this post I replicate setup you given with multiple “esp32’s” at my desk, but I encountered strange problem -> one of the ESP32 reboots again and again each time it tries to publish. But I figure out the what was the problem with help of your tutorial (for esp8266) solution – In case of MQTT multiple connections we have to assign different device ID’s to each ESP.

    Thank you for all your tutorials, very useful to hobbyist like me. I always recommends your blog and Coarses to my friends.

    Thanks and Regards

    Reply
    • Hi.
      Thank you so much for supporting our work.
      Indeed a “search box” is something that will be very useful. However, adding a search box that actually works well, it’s not as straightforward as it seems. But, yes, we want to improve and we’re working on it. We have lots of tutorials that sometimes are not easy to “find”. Thank you for your suggestion.
      I’m glad you got your MQTTT project working. Now, with an ID for each ESP32, is everything working fine?
      Regards,
      Sara

      Reply
  5. Hi Rui,
    great work and thanks for your great video courses.

    I try to adapt your code to my private mqtt project and add the following after lines:
    const char* mqtt_server = “192.168.2.122”;
    const char* mqttUser = “quito”;
    const char* mqttPassword = “XXXXXXXX“;

    WLAN connect ok, but no connection to the mqtt server is possible.

    How can i fix this?

    Best Regards
    Guido

    Reply
  6. Hello my friend.
    What is the best library for used MQTT on ESP32?

    Pubsubclient or Async?

    In the your book ESP32 you used Async.

    Best regards.
    Thank you for your tutorial

    Reply
  7. HI, I followed your instructions and got to the point where I got a error message on the Node Red when i was trying to deploy the nodes. Trouble shooting brought me to a point where I don’t get any feedback from the ESP32 in the Serial monitor. any further advice?
    the sketch is uploading OK, no error messages.

    Reply
  8. Hie I wanted to do plant monitoring with IoT.I just started following your website, up to WiFi scanning it is working perfectly fine after that after that when I try compiling your code I am getting two errors.one main error is….

    Multiple libraries were found for “WiFi.h”
    Used: C:\Users\admin\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.1\libraries\WiFi
    compilation terminated.

    Not used: C:\Program Files (x86)\Arduino\libraries\WiFi
    exit status 1

    other error is related to DHT sensors library which is from other post of yours where DHT.h file is missing in that folder..

    Please help me I am struggling from two days……

    Reply
  9. I did all the things accordingly but still showing this this message again and again. Please help me, please see my code below.

    Attempting MQTT connection…failed, rc=5 try again in 5 seconds

    /*********
    Rui Santos
    Complete project details at https://randomnerdtutorials.com
    *********/

    #include
    #include
    #include
    #include
    #include

    // Replace the next variables with your SSID/Password combination
    const char* ssid = “”;
    const char* password = “”;

    // Add your MQTT Broker IP address, example:
    //const char* mqtt_server = “192.168.1.144”;
    const char* mqtt_server = “192.168.1.101”;

    WiFiClient espClient;
    PubSubClient client(espClient);
    long lastMsg = 0;
    char msg[50];
    int value = 0;

    //uncomment the following lines if you’re using SPI
    /*#include
    #define BME_SCK 18
    #define BME_MISO 19
    #define BME_MOSI 23
    #define BME_CS 5*/

    Adafruit_BME280 bme; // I2C
    //Adafruit_BME280 bme(BME_CS); // hardware SPI
    //Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
    float temperature = 0;
    float humidity = 0;

    // LED Pin
    const int ledPin = 5;

    void setup() {
    Serial.begin(115200);
    // default settings
    // (you can also pass in a Wire library object like &Wire2)
    //status = bme.begin();
    if (!bme.begin(0x76)) {
    Serial.println(“Could not find a valid BME280 sensor, check wiring!”);
    while (1);
    }
    setup_wifi();
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);

    pinMode(ledPin, OUTPUT);
    }

    void setup_wifi() {
    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print(“Connecting to “);
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(“.”);
    }

    Serial.println(“”);
    Serial.println(“WiFi connected”);
    Serial.println(“IP address: “);
    Serial.println(WiFi.localIP());
    }

    void callback(char* topic, byte* message, unsigned int length) {
    Serial.print(“Message arrived on topic: “);
    Serial.print(topic);
    Serial.print(“. Message: “);
    String messageTemp;

    for (int i = 0; i 5000) {
    lastMsg = now;

    // Temperature in Celsius
    temperature = bme.readTemperature();
    // Uncomment the next line to set temperature in Fahrenheit
    // (and comment the previous temperature line)
    //temperature = 1.8 * bme.readTemperature() + 32; // Temperature in Fahrenheit

    // Convert the value to a char array
    char tempString[8];
    dtostrf(temperature, 1, 2, tempString);
    Serial.print(“Temperature: “);
    Serial.println(tempString);
    client.publish(“esp32/temperature”, tempString);

    humidity = bme.readHumidity();

    // Convert the value to a char array
    char humString[8];
    dtostrf(humidity, 1, 2, humString);
    Serial.print(“Humidity: “);
    Serial.println(humString);
    client.publish(“esp32/humidity”, humString);
    }
    }

    Reply
  10. Hi,

    In your code that you provided, at the top section, you have these 2 lines
    —————————-
    WiFiClient espClient;
    PubSubClient client(espClient);
    ——————————-

    under the reconnect () section…..
    —————————-
    void reconnect() {
    // Loop until we’re reconnected
    while (!client.connected()) {
    Serial.print(“Attempting MQTT connection…”);
    // Attempt to connect
    if (client.connect(“ESP8266Client”)) {
    Serial.println(“connected”);
    —————————

    What is this “ESP8266Client” ? Is this an error ?

    Regards,
    Ong Kheok Chin

    Reply
  11. Hi!
    Great doc!

    Using PlatformIO I did try this code, but when uploading to Arduino I get a warning and that warning is causing the same issue as ONG KHEOK CHIN.

    Probably related.
    Error is the following:

    ————————————————————————————————–
    test.cpp: In function ‘void callback(char*, byte*, unsigned int)’:
    test.cpp:274:23: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
    for (int i = 0; i < length; i++) {
    ^
    ————————————————————————————————–

    There seems to be a problem with the FOR condition…

    Any ideas?
    Thx alot!

    Reply
  12. Hi Rui/Sara,

    I followed your tutorial for “ESP32 with Multiple DS18B20 Temperature Sensors” which is exactly what i need for a project for the factory that i work in. I managed to alter it slightly to display 5 sensors. This is working well.

    The second thing that I wanted to do is display these readings on a webpage, and thirdly i wanted to store the readings in a database.

    So for the second part of my project I followed the link from the first tutorial, which took me to this tutorial “ESP32 MQTT – Publish and Subscribe with Arduino IDE”.

    Unfortunately, you have now jumped to using a different sensor (the BME280) and you are only using one sensor.

    I am really struggling to make the jump from one to the other and i don’t think that learning about the BME280 is really going to help.
    I looked at the forum to see if anyone else has asked a similar question. There was one person, but he seems to be following a python tutorial.

    Do you have a link to any other tutorial which links the “ESP32 with Multiple DS18B20 Temperature Sensors” to allow me to Publish and Subscribe the data to MQTT?

    Reply
  13. Just a note – bme is by default (as far as I know) initialized on 0x77 not on 0x76. It took me few minutes and checking wires to realize that this may be the problem 🙂

    And thx for good article.

    Reply
  14. nice tutorial! just a small note, that is maybe confusing..
    mqtt_basic example the inTopic and outTopic messages are the opposite from here..
    we should publish to esp32/input..because we are waiting for input signal..i think the name is a little confusing..

    Reply
  15. Congratulations. It is a very valuable tutorial. I would like to know if you could publish the code where instead of using wifi communication, the 3G module sim5320 or similar would be used. It would be of great help to me.
    Thank you.

    Reply
    • Hi Fernando.
      We don’t have any tutorial about the SIM5320.
      We have a tutorial that uses SIM800. The library we use is also compatible with the SIM5320.
      So, you can probably use our tutorial with your board. Here it is: https://randomnerdtutorials.com/esp32-sim800l-publish-data-to-cloud/
      I hope this helps.
      I’m sorry for the delay in our response.
      We receive lots of comments on different tutorials every day. It is very difficult to keep track of all the questions.
      Regards,
      Sara

      Reply
  16. I have three ESP32 units publishing on the same topic to a raspberry pi. Once a unit is connected and another one connects to it, the connection of the first unit get lost.

    Is it possible to publish/recieve simulatniously or at least without no disconnect by using MQTT?

    Reply
  17. Nice tutorial! I already have it working via Wifi but now I want to sent the MQTT message via the BG96 modem which is connected to a UART of my ESP32. I already have configured the BG96 to connect to the APN of my SIM card provider. How do I configure the project in a way that the MQTT data is sent via the BG96?

    Thanks,

    Tjerk

    Reply
  18. hello sir thanks for your amazing work, by following your guide i am able publish and subscribe mqtt channel successfully. it works fine. but i need slight modification. i am running mqtt broker on my windows pc. in case of power failure I miss some sensor readings. I want to store sensor reading on esp32 in case of mqtt broker got disconnected so that when connection is restored esp32 will publish the sensor reading along with time. I searched on google but find nothing can you guide me little bit.

    Reply
  19. I am new in this field currently I am using pubsubclient for my project bu pubsubclient block my main loop if mqtt unavailable can I use async-mqtt-client with thingsboard if yes please let me know how can i configure async-mqtt-client with thingsboard.

    Reply
  20. Olá Sara,
    Mistake in this line of your code ?
    // Attempt to connect
    if (client.connect(“ESP8266Client”)) {……..

    Should be if (client.connect(“espClient”)) {…….. ?

    Cumprimentos

    Reply
  21. hi,I haven’t been able to do this example, I’m using everything the same, and I already check the mosquitto broker on my raspberry but nothing that works for me comes out rc=-2 in the Arduino serial,what can I do?

    Reply
  22. Great tutorial Rui & Sarah.
    but 1 question, what is “ESP8266Client” in :
    if (client.connect(“ESP8266Client”)) {
    Serial.println(“connected”);
    // Subscribe
    client.subscribe(“esp32/output”);
    if i’m using an ESP32 board, should i change it to ESP32Client instead?
    because now i get rc=-2 error

    Reply
  23. hello
    i have create a node-red setup (raspberru-pi4) together with an esp32 that is publishing/subscribe on topics. i have a second esp32 that contains the same program as the first esp32. when running only 1 esp32 is receiving the mqtt messaging . why doesnt the second esp32 cant receive the data?

    Reply
  24. Hi,
    I have a weather station and the values ​​are transferred to a web server, I would also like to transfer the values ​​to my SmartHome instance (FHEM, ioBroker) via MQTT. But I am an absolute beginner and unfortunately I do not get that realized. Can someone help me?
    Greetings from Germany

    Reply
      • Hi,
        it doesn’t really matter whether it is done with NodeRed or HomeAssistent or ioBroker, I can’t do the sketch with WebServer and MQTT

        Regards
        Thomas

        Reply
  25. Hi Sara/Rui,

    Using some part of this code I detect that in the callback() function you first print the values for topic and message and after this the code read the input stream. I think the right code must be in the form:
    for (unsigned int i = 0; i < length; i++)
    {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
    }
    Serial.print(“Message arrived on topic: “);
    Serial.print(topic);
    Serial.print(“. Message: “);
    String messageTemp;

    Reply
  26. Slight Problem. I am using a Wemos D1 esp8266 communicating to a Raspberry Pi containing Mosquitto and the Subscriber. I am trying to add a second parameter after reading a Potentiometer, But the serial monitor and the Mosquitto monitor only shows the pot value. Other inputs from Buttons work OK. This is my example.
    if(analogRead(analogInPin) < 475)
    {
    pana = (52 – (analogRead(analogInPin)/9));
    // From: https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/
    char ptempString[8];
    dtostrf(pana, 1, 2, ptempString);

    String payload = ("Pright", ptempString);
    Button_State = PRESSED;
    delay(500);
    return payload;
    }

    if(digitalRead(ButtonLeft) == PRESSED)
    {
    String payload = "motorleft";
    Button_State = PRESSED;
    return payload;
    }

    I lose ‘Pright’ on the receiver. Can you see what I have done wrong?
    Thanks,

    Reply
  27. Can a esp-32 camera mqtt to a raspberry pi? I’m too far from the router for the esp32 cam to connect but I am near a raspberry pi that is connected to an ethernet cable that is already mqtt’ing to some esp8266 boards. Not sure if there is a tutorial on something like this or not. A search on the net didn’t turn up anything.

    Thanks,

    Bob

    Reply
  28. Hello
    do you know how to connect three esp32 as a slave and one esp32 as a master use mqtt broker?
    in this case three of the esp32 who are work as a slave connecting to humidity sensor and after have the value of the sensor the esp as a slave send or publish the message to master. if the value is 1790 the relay is stay off.
    how to intialize the slave in a master source code?
    how is the source codee in a slave?
    i have looking for the example source code but i don’t get it.

    i do hope you can help
    best regard

    Nurul from INA

    Reply
  29. Hello,I really like your example .Thanks for sharing . I am now making a system that is like this:
    A raspberry pi is at my home ,while the Esp32s are in my garden. Is it possible to use mqtt trough internet? Thank you!
    Luke lin from Taiwan

    Reply
  30. Hi!
    Great courses and so many of them to learn from!
    Now I made first the (ESP32 MQTT – Publish BME680 Temperature, Humidity, Pressure, and Gas Readings (Arduino IDE)) which worked fine. Then I wanted to try subscribing from Node-red to ESP32. So I looked at this current one (ESP32 MQTT – Publish and Subscribe with Arduino IDE). Now I was confused,the approach is different and using PubSubClient.h instead of AsyncMqttClient.h ? -I managed to get it work using AsyncMqttClient.h and the nodes from this current example. Could you open up the difference between the two ways and tell me which is better. -And why. 😉
    Many thanks,
    Janne from Finland

    Reply
    • Hi.
      The PubSubClient is a synchronous library and the AsyncMQTTClient is an asynchronous library.
      synchronous: the code is run linearly. You can’t do other tasks while listening for incoming messages, for example
      asynchronous: the code works with events and callback functions, when something happens a function will run. You can execute other tasks meanwhile.
      Those are the most popular MQTT libraries to use with the ESP32. One is not better than the other. They are different. You can use the one you like most or the one you think is more suitable for your projects.
      I hope this helps.
      Regards,
      Sara

      Reply
  31. Hi friends,

    I’ve some issues with the PubSubClient.
    If the mqtt connection looses then the ESP stops working and also the watchdog can not bring it to live.
    With the Async-mqtt-client there is an other problem.
    When a message is coming in, the ESP hangs to long in the “void onMqttMessage()” funktion.
    Booth is not acceptable for critical applications.

    Do you have some ideas? is there any other library?

    Best wishes

    Reply
  32. Hey,
    The explanation of the MQTT in the above code is pretty good.
    I had a problem, hope you may know the solution for it.
    I am trying to publish from one esp32 and subscribe the topic in another esp32. So, whenever the esp32 that publishes the data, the subscribed esp32 is trying to get the data but it ends up with reconnecting. I don’t know why.
    I hope you understand what is my problem.
    Looking forward to reply

    Reply
  33. FYI – be sure to rename the client to something unique, especially if using a public broker. I was trying to connect test.mosquitto.org and was repeatedly being kicked off before I realized this. There are probably a lot of people demo’ing this tutorial! Congratulations to the authors as this is really helping me.

    Reply
  34. Hi,
    I’m a newbie and I found yourn courses very useful.
    However I have a problem with finding a Raspberry Pi at a reasonable price since it seems that they’re all out of stock.
    Do you think that Orange Pi 4 could be a valid option to use for running Node-Red ?
    Thanks for your help
    PS If I find a Raspberry Pi 3 a+ with only 512 Mb RAM would it be OK for the project ?

    Reply
    • Yes.
      You can run node-red on orange pi. However, we don’t have any tutorials about that.
      A Raspberry Pi 3 will work, but might be a bit slow.
      Regards,
      Sara

      Reply
      • Thanks for your prompt answer.
        Since I need to collect humidity and temperature data from two BME280 connected to two ESP32 placed in two different rooms every 3 or 5 minutes would a Raspberry Pi 3 a+ too slow or could be OK ? Sorry for the maybe silly question but – as I told before – I’m a newbie
        Best
        Bruno

        Reply
  35. Hi,
    I’m a newbie .I just want to know which ip address should I put in mqtt_server variable. I am running mqtt mosquitto and node-red on home Assistant which is running on my windows machine using VM.
    Thanks for this amazing tutorial.

    Reply
  36. another amazing tutorial, thank you again. How would I arrange code so that the ESP32 goes to sleep for X minutes after sending a reading?

    Reply
  37. Would it be possible to read MQTT data rather than initiate led’s ?
    If so would appreciate knowing how.

    Reply
  38. I have been able to answer my own question.
    It was already done in “void callback”. Changed the client name to what was required to read & converted the message string into float.

    Reply
  39. (Quais modelos de Raspberys podem ser utilizados nesses projeto, ou só o Raspbery 4 tem as caracteristicas tecnicas nesecsarias para este projeto?) – Portuguese

    (Which Raspberry Pi models can be used in this project, or does only Raspberry Pi 4 have the necessary technical features for this project?) – English

    Reply
    • Hi.
      You can use Raspberry Pi 2, 3, 4 ou Raspberry Pi Zero W.
      All these models should be compatible with the project.
      Regards,
      Sara

      Reply
  40. Thank you for your tutorial. I am trying to use the sketch above for an ESP32Wroom and I keep getting “Attempting MQTT connection…failed, rc=-2try again in 5 seconds.
    I have confirmed that my mosquitto connection is working correctly. I have changed nothing on the sketch included. I am using a Raspberry pi 5. Any suggestions? I have proofread the sketch more times than I can count. Thank you.

    Reply
    • Hi.
      You need to modify your sketch with your network credentials and mosquitto broker username (the Raspberry Pi IP address) and password.
      Regards,
      Sara

      Reply
      • Hi Sara,
        I too am having this issue. It would be helpful if this tutorial expands a little to include authentication with a MQTT broker. I searched via google and found GitHub posts with examples that use different approaches, and I am confused at why “ESP8266Client” is used when this is a ESP32 device reaching out. Just saying, thank you!

        Reply
        • Hi.
          Thanks for pointing that out.
          You’re right. It should be ESP32 Client (this was previously adapted from an ESP8266 project).
          To use username and password, pass the client name, username and password to the connect method.

          client.connect(“CLIENT_NAME”, “MQTTUSERNAME”, “MQTTPASSWORD”)

          Thanks for your comment. I realized we need to update this tutorial asap.

          Regards,
          Sara

          Reply
  41. Hi! I have a problem importing the Node-RED flow because it says that some nodes are not recognized. How can I solve this?

    Reply
  42. HI
    Im doing a project that follows the same structure as this tutorial, with the difference that instead of reading the sensor with the esp32, I am reading (3) dht22 sensors with an Arduino and sending the data via serial communication to the esp32 .
    At the time of publication I added a debug message that if the publication was made it would print “Published”, but it is happening that often the 3 “Published” messages appear but there are topics without publications, for example the topic of sensor 1 always receives its data but the other two dont.
    Before publishing, I print the data received from the Arduino and all the data from all the sensors are ok.

    I can’t find a solution to this problem, do you have any idea what could it be ?

    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.