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
- You should be familiar with the Raspberry Pi – read Getting Started with Raspberry Pi.
- You should have the Raspbian operating system installed in your Raspberry Pi – read Installing Raspbian Lite, Enabling and Connecting with SSH.
- You need Node-RED installed on your Pi and Node-RED Dashboard.
- Learn what’s MQTT and how it works.
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):
- Raspberry Pi – read Best Raspberry Pi 3 Starter Kits
- ESP32 DOIT DEVKIT V1 Board – read ESP32 Development Boards Review and Comparison
- BME280 sensor module
- 1x 5mm LED
- 1x 220 Ohm resistor
- Breadboard
- Jumper wires
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.
- Windows instructions – ESP32 Board in Arduino IDE
- Mac and Linux instructions – ESP32 Board in Arduino IDE
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).
- Click here to download the PubSubClient library. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get pubsubclient-master folder
- Rename your folder from
pubsubclient-masterto pubsubclient - Move the pubsubclient folder to your Arduino IDE installation libraries folder
- 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:
- Click here to download the Adafruit-BME280 library. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get Adafruit-BME280-Library-master folder
- Rename your folder from
Adafruit-BME280-Library-masterto Adafruit_BME280_Library - Move the Adafruit_BMPE280_Library folder to your Arduino IDE installation libraries folder
- 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:
- Click here to download the Adafruit_Sensor library. You should have a .zip folder in your Downloads folder
- Unzip the .zip folder and you should get Adafruit_Sensor-master folder
- Rename your folder from
Adafruit_Sensor-masterto Adafruit_Sensor - Move the Adafruit_Sensor folder to your Arduino IDE installation libraries folder
- 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);
}
}
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:
- Learn ESP32 with Arduino IDE Course
- Alexa (Echo) with ESP32 and ESP8266 – Voice Controlled Relay
- Build an All-in-One ESP32 Weather Station Shield
- ESP32 Publish Sensor Readings to Google Sheets
- ESP32 with DHT11 DHT22 Temperature Humidity Web Server
- ESP32 Web Server with Arduino IDE
We hope you’ve found this tutorial useful.
Thanks for reading.
Great tutorial! Thank you.
Thank you for reading Val. I’m glad you liked it!
Regards,
Rui
Great project, would it be possible to expand this to read 3 BME280 on 1 RPi?
Ian
Yes, you should be able to use as many BME as you want (as long as you have enough pins to use the CS).
Regards,
Rui
Thanks, I did mean to say 3 BME280 with 3 ESP32 to one RPi?
Excuse my ignorance but what is “the CS”?
Regards
Ian
If you need multiple ESPs, you can use the exact same code and you don’t need to change the CS (Chip Select pin). You simply need to publish the messages on different MQTT topics
Thanks, just wating for the ESP’s to arrive and I’ll give it a try
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?
It’s ok I’ve found them, thanks anyway
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!
Hi Simon.
The sensor readings are not stored in any database. If you restart node-red or delete the node, they will be lost. When it comes to the charts, it only saves readings from a few hour before.
But you can integrate with a database like SQlite for example. You can take a look at the following tutorials:
https://randomnerdtutorials.com/sqlite-with-node-red-and-raspberry-pi/
https://randomnerdtutorials.com/sqlite-database-on-a-raspberry-pi/
Regards,
Sara 🙂
Sara, Node-Red lets you configure how long messages are kept in charts (but not gauges). The setting is the “X-axis last <#> OR <####> points”.
I publish once per minute, and can keep 3 days of data on each chart. The dashboard runs a little slow with that many data points, because I have 27 charts (from multiple ESPs).
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
Yes. That’s what happens with this example.
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
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
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
Hi Guido.
Is the MQTTT broker running ok?
Can you test your broker and see if it is working fine?
https://randomnerdtutorials.com/testing-mosquitto-broker-and-client-on-raspbbery-pi/
Regards,
Sara 🙂
Hi Guido
Could you please check …
// Attempt to connect
if (client.connect(“ESP32Client”, mqttUser, mqttPassword )) {
Serial.println(“connected”);
Serial.println(“connected”);
// Subscribe
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
Hi Angel.
We prefer the Async library.
In our opinion, it works better than the Pubsubclient.
Regards,
Sara
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.
Hi Hans.
What error did you get on Node-RED?
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……
Hi Madhu.
The Wi-Fi problem should be solved if you follow bullet 5 of our troubleshooting guide: https://randomnerdtutorials.com/esp32-troubleshooting-guide/
To use DHT you need the following libraries:
– DHT library: github.com/adafruit/DHT-sensor-library
– ADafruit sensor driver library: github.com/adafruit/Adafruit_Sensor
I hope this helps.
Regards,
Sara
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);
}
}
Hi.
That means that the ESP32 is not able to connect to your broker. Please double check that your broker is properly set up.
You can follow this tutorial to check if your broker is working properly: https://randomnerdtutorials.com/testing-mosquitto-broker-and-client-on-raspbbery-pi/
Regards,
Sara
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
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!
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?
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.
It will depend on your module, because their I2C address sometimes is different. I always recommend running an I2C scanner to check the address of your module.
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..
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.
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
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?
Hi.
Can you try the AsyncMQTT library to do that?https://github.com/marvinroger/async-mqtt-client
I think you won’t have that problem.
Regards,
Sara
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
Hi.
Your question is being answered here: https://rntlab.com/question/mqtt-via-uart/
Regards,
Sara
Thank you, this is really helpfull.
However the MQTT connect is a blocking function. I learned that i can use the second ESP32 core (https://randomnerdtutorials.com/esp32-dual-core-arduino-ide/) and let the connect run there.
Is there a simple solution that lets de connect function run only 3 or 5 times and then just stops?
Thank you for your time,
Eric
Hu Eric.
Instead of the PubSubClient library, use the AsyncMQTTClient library instead.
See this tutorial for an example: https://randomnerdtutorials.com/esp32-mqtt-publish-bme280-arduino/
Regards,
Sara
Thank you so much for the update, this will help me very much.
keep up the good work!
Eric
The tutorial worked wonderwell! I like the structure where I can find more detailed instructions.
Hi.
Here you can find all our MQTT related tutorials: https://randomnerdtutorials.com/?s=mqtt
Regards,
Sara
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.
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.
Olá Sara,
Mistake in this line of your code ?
// Attempt to connect
if (client.connect(“ESP8266Client”)) {……..
Should be if (client.connect(“espClient”)) {…….. ?
Cumprimentos
hi it’s a good work
i just want ask you if i can repalce the raspberry with my laptop ??
Hi.
Yes, you can run mosquitto broker on your computer.
Regards,
Sara
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?
Nice tutorial.
I took inspiration from your project to make my project a little more complex. I used EMQ X Edge as MQTT Broker installed on Rpi 4 and relays connected to ESP32. On my GitHub repository I have published the source code and the description of the project https://github.com/amusarra/esp32-mqtt-publish-subscribe.
That’s great!
Thanks for sharing it.
Regards,
Sara
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
Hi.
For the ESP32, you use WiFiClient.
Regards,
Sara
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?
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
Hi.
Unfortunately, we don’t have any tutorials about MQTT with Home Assistant.
Regards.
Sara
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
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;
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,
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
Cercavo informazioni su come settare il QoS dei messaggi
Ciao!
What is the VALUE variable for? line 24.
“int value = 0;”
thanks
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
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
Hi.
Yes. You need to use a cloud MQTT broker.
You can use a commercial MQTT broker or you can create your own cloud MQTT broker, for example: https://randomnerdtutorials.com/cloud-mqtt-mosquitto-broker-access-anywhere-digital-ocean/
Regards,
Sara
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
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
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
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
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.
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 ?
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
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
That board will be more than enough for your project.
Regards,
Sara
Thanks
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.
Hi
You need to use the virtual machine’s IP address.
Regards,
Sara
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?
Hi.
Check the deep sleep tutorial: https://randomnerdtutorials.com/esp32-timer-wake-up-deep-sleep/
Regards,
Sara
Would it be possible to read MQTT data rather than initiate led’s ?
If so would appreciate knowing how.
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.
(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
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
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.
Hi.
You need to modify your sketch with your network credentials and mosquitto broker username (the Raspberry Pi IP address) and password.
Regards,
Sara
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!
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
Hi! I have a problem importing the Node-RED flow because it says that some nodes are not recognized. How can I solve this?
Hi.
did you install node-red dashboard? https://randomnerdtutorials.com/getting-started-node-red-dashboard/
Regards,
Sara
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 ?