How to Connect ESP32 to MQTT Broker

How to Connect ESP32 to MQTT Broker

IoT is a system that connects with the devices that are accessible through the internet. There are number of cloud platforms and protocols, MQTT is one of the most used IoT protocol for IoT projects. In our previous tutorial, we have connected MQTT with Raspberry Pi and ESP8266. Now, we are establishing connection between MQTT server and ESP32.

ESP32 is a Successor of popular ESP8266 Wi-Fi module, with many advanced features such as this module is a dual core 32-bit CPU with built-in Wi-Fi and dual-mode Bluetooth with sufficient amount of 30 I/O pins.

While, MQTT stands for Message Queuing Telemetry Transport, it’s a system where we can publish and subscribe messages as a client. By using MQTT you can send commands to control outputs, read and publish data from sensors and much more. There are two main terms in MQTT i.e. Client and Broker.

 

What is MQTT Client & Broker? 

MQTT Client: An MQTT client runs a MQTT library and connects to an MQTT broker over a network. Both publisher and subscriber are MQTT clients. The publisher and subscriber refer that whether the client is publishing messages or subscribing to messages.

MQTT Broker: The broker receives all messages, filter the messages, determine who is subscribed to each message, and send the message to these subscribed clients.

 

Now, in this tutorial we will explain how to connect to a MQTT broker and subscribe to a topic using ESP32 and Arduino IDE libraries.

 

Components Required

  • ESP32
  • Cloud MQTT

 

Cloud MQTT Account Setup

To set up an account on Cloud MQTT navigate to its official website (www.cloudmqtt.com) and sign up using your email.

MQTT Account Setup for ESP8266

 

After login, click on ‘+ Create New Instance’ to create a new instance.

Create New Instance on MQTT Account for ESP8266

 

Now enter your instance name and select ‘Cute Cat’ in plan option.

Select Plan for MQTT Account

 

In new tab select region and click on ‘Review’.

Review MQTT Account Setup for ESP8266

 

Your instance is created and you can view your details like user and password.

Login to MQTT Account for ESP8266

 

ESP32 MQTT Broker Code Explanation

The complete code for Connecting ESP32 with MQTT broker is given at the end. Here, we are using Arduino IDE to program ESP32. First, install WiFi.h library and PubSubClient library.

PubSubClient library allows us to publish/subscribe messages in topics.

#include <WiFi.h>
#include <PubSubClient.h>

 

Now declare some global variables for our WiFi and MQTT connections. Enter your WiFi and MQTT details in below variables:

const char* ssid = "CircuitLoop"; // Enter your WiFi name
const char* password =  "circuitdigest101"; // Enter WiFi password
const char* mqttServer = "m16.cloudmqtt.com";
const int mqttPort = 12595;
const char* mqttUser = "eapcfltj";
const char* mqttPassword = "3EjMIy89qzVn";

 

In the setup_wifi function, it will check the WiFi, whether it is connected to network or not, also give the IP address and print it on the serial monitor.

void setup_wifi() {
    delay(10);
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    randomSeed(micros());
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

 

In the below, while loop function, it will connect to the MQTT server and will print it on the serial monitor. This process will run in a loop until it gets connected.

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(),MQTT_USER,MQTT_PASSWORD)) {
      Serial.println("connected");
      //Once connected, publish an announcement...
      client.publish("/icircuit/presence/ESP32/", "hello world");
      // ... and resubscribe
      client.subscribe(MQTT_SERIAL_RECEIVER_CH);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);

 

Now we will specify a call back function and in this function, we will first print the topic name and then received message.

void callback(char* topic, byte *payload, unsigned int length) {
    Serial.println("-------new message from broker-----");
    Serial.print("channel:");
    Serial.println(topic);
    Serial.print("data:"); 
    Serial.write(payload, length);
    Serial.println();
}

 

Testing MQTT with ESP32

Now to test the code upload this code into ESP32 using Arduino IDE and open the serial monitor.

Connecting ESP32 to Wifi for MQTT Broker

 

To subscribe and publish to MQTT topics, a Google Chrome application MQTTlens will be used. You can download the app from here.

Launch this app and set up a connection with MQTT broker. To setup, connection click on ‘connections’ and in next window enter your connection details from Cloud MQTT account.

Launch MQTTlens for Connecting with ESP8266

 

Save this connection, and  now you can subscribe and publish a message on your MQTT broker using ESP8266.

To subscribe or publish a message enter your topic name in subscribe and publish option and enter the default message.

Setup Account on MQTTlens

 

Your message will be shown on serial monitor as shown in the above image of the serial monitor.

Testing MQTT Broker with ESP32

 

Hence, we have successfully connected the MQTT broker with ESP32. Stay Tuned with us for more amazing IoT projects.

Code

#include <WiFi.h>
#include <PubSubClient.h>


// Update these with values suitable for your network.
const char* ssid = "CircuitLoop";
const char* password = "circuitdigest101";
const char* mqtt_server = "m16.cloudmqtt.com";
#define mqtt_port 12595
#define MQTT_USER "eapcfltj"
#define MQTT_PASSWORD "3EjMIy89qzVn"
#define MQTT_SERIAL_PUBLISH_CH "/icircuit/ESP32/serialdata/tx"
#define MQTT_SERIAL_RECEIVER_CH "/icircuit/ESP32/serialdata/rx"

WiFiClient wifiClient;

PubSubClient client(wifiClient);

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(".");
    }
    randomSeed(micros());
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(),MQTT_USER,MQTT_PASSWORD)) {
      Serial.println("connected");
      //Once connected, publish an announcement...
      client.publish("/icircuit/presence/ESP32/", "hello world");
      // ... and resubscribe
      client.subscribe(MQTT_SERIAL_RECEIVER_CH);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void callback(char* topic, byte *payload, unsigned int length) {
    Serial.println("-------new message from broker-----");
    Serial.print("channel:");
    Serial.println(topic);
    Serial.print("data:");  
    Serial.write(payload, length);
    Serial.println();
}

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(500);// Set time out for 
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  reconnect();
}

void publishSerialData(char *serialData){
  if (!client.connected()) {
    reconnect();
  }
  client.publish(MQTT_SERIAL_PUBLISH_CH, serialData);
}
void loop() {
   client.loop();
   if (Serial.available() > 0) {
     char mun[501];
     memset(mun,0, 501);
     Serial.readBytesUntil( '\n',mun,500);
     publishSerialData(mun);
   }
 }
 

3715 Comments

Esperio Review – Some Facts About This Offshore Fraud
INBROKERS REVIEWS, FOREX SCAMSTAG:FOREX SCAM, SCAM REVIEW0
Forex and CFD trading is a very specific industry. It can be very risky, therefore we are always looking for reliable and trusted companies. If you were hoping that Esperio broker is the one, you were wrong.

A company that doesn’t have a license and has a fake virtual address is not the one we should trust. They are based officially in St.Vincent and Grenadines, but in reality, it is most probably different. Since on the same address, we managed to find many different scamming companies. Let’s take a look at this Esperio review for more info.

Furthermore, we highly recommend that you avoid the scam brokers Vital Markets, Sky Gold Market, and DamkoNet.

Broker status: Unregulated Broker
Regulated by: Unlicensed Scam Brokerage
Scammers Websites: Esperio.org
Blacklisted as a Scam by: NSSMC
Owned by: OFG Gap. LTD
Headquarters Country: St. Vincent and Grenadines
Foundation year: 2021
Supported Platforms: MT4/MT5
Minimum Deposit: 1$
Cryptocurrencies: Yes – BTC, ETH, XRP
Types of Assets: Forex, Commodities, Indices, Shares, Cryptocurrencies
Maximum Leverage: 1:1000
Free Demo Account: No
Accepts US clients: No
report a scam.
Esperio Is a Non – Licensed Fraud Broker?
Financial Services Authority from St. Vincent and Grenadines already stated that they are unauthorized to provide licenses for Forex and CFD trading. Therefore, that country doesn’t have legal supervision.

If you take a look at the countries that Esperio is operating in, you will see that they don’t have any other licensing.

Since they are scamming traders from Italy, the UK, Germany, Poland, and more, you would expect them to have FCA or BaFin regulations. As you could guess, they don’t.

High leverages, bonuses and cryptocurrencies. Everything that is not regulated is available with Esperio broker. That being said, you don’t want to deal with something when you don’t know the terms.

Arguments For Trading With a Licensed Broker
Since we checked the database of Tier 1 regulators ( FCA, BaFin and ASIC ) and found nothing, we can confirm that this is a complete scam. These Tier 1 regulators are offering stability and security to clients.

You know that your funds are at any point in time protected and that nobody can scam you. Any terms and conditions are strictly controlled by the regulator.

Warnings From Financial Regulators
Esperio Warnings From Financial Regulators
Ukrainian regulatory body NSSMC has issued a warning against Esperio broker. That happened in August 2022. It’s just a matter of time before other countries will add their warnings against this broker.

That’s a time when these brokers vanish and just do a rebranding with the same principle. Be careful.

Does Esperio Offer MetaTrader 5?
Besides MT4, an industry standard, they offer as well MT5 trading platform. It has higher functionality and a variety of trading tools available. Starting from social trading, advanced EA trading tools and indicators and many more.

This is the only thing we could give credit for to the company in this Esperio review.

What Financial Instruments Does Esperio Include?
Financial classes like in many other companies are available. So, if you go with a regulated company, you are not missing anything. Those classes are:

Forex USD/JPY, EUR/NZD, USD/CAD
Indices DAX30, FTSE100, BE20
Commodities crude oil, platinum, gold
Shares BMW, Tesla, Visa
Cryptocurrencies ETH, BTC, BNB
Like with any CFD trading company, especially non-regulated, you should be extremely careful. Leverages are mostly higher than allowed in regulated companies.

Areas Of Esperio
The list of countries they are reaching out to is quite big. Yet, there are most probably many more unconfirmed. Countries, they are scamming traders from, are:

UK
Italy
Germany
Poland
Serbia
Netherlands
Romania
Even Esperio reviews are saying the same thing. People over and over losing money with them and not being able to withdraw their profits.

Esperio And The Types Of Accounts Offered
The company offers 4 different account types:

Esperio Standard
Esperio Cent
Esperio Invest
Esperio MT4 ECN
For any account mentioned above you get certain benefits. Spreads, commissions, overnight swaps and bonuses are the fields they are changing to lure you into their net. As for the minimum requirement, for any account, it is 1$.

You already know that nothing is for free. So, when you invest your first dollar, expect to be asked for more.

Esperio Offers Free Demo Accounts?
The company doesn’t offer a demo account. However, it is not needed since the minimum investment is only 1$. But, if you want to keep your information private, a demo account sounds like a good option here.

Nobody wants to disclose personal information and banking information to a fraudulent company.

Esperio Deposit and Withdrawal Policies
As a payment option, Esperio offers Visa/Mastercards, bank transfers and cryptocurrency transfers. Some of the systems are charging a commission as well. Detailed conditions are only available if you register.

Withdrawing the funds is going to be trouble. We checked other Esperio reviews and we found that people were unable to get any of the funds back. Most of the time the broker is asking you to pay some additional fees before funds are released.

Of course, if you fall for that story, they know they extracted everything from you. And you never hear back again from them.

Esperio Terms and Conditions
If the company is offering leverages up to 1:1000 you know they can’t have regulations. The reason for that is that regulatory bodies don’t allow it higher than 1:30.

Another speculative thing about this broker are bonuses that they are offering. This is as well not allowed according to regulations. To sum it up, any of your funds won’t be safe here no matter what advertisement they put out.

Esperio Broker Scammed You? – Please Tell Us Your Story
We like to hear our clients’ stories. That way, we can find out if the broker has implemented something new in their tactics. As well, as that way you can protect other people from being scammed.

In the case that it was you, don’t be ashamed. It can happen to anyone. Yet there is a solution. A chargeback works like a charm. Don’t waste any more time and reach our experts for the first step!

What Is the Chargeback Procedure?
This is a money reversal procedure. Your bank knows where the money is going. If you request it at the right time, you can get your funds back. Get in touch today to see how!

What Is Esperio?
Esperio broker is a non-licensed offshore company. They operate from St. Vincent and Grenadines, allegedly.

Is Esperio a scam Broker?
If the regulatory body of some country is issuing a warning, then you can say it for sure.

Is Esperio Available in the United States or the UK?
This broker only offers services to clients coming from the UK, but not US.

Does Esperio Offer a Demo Account?
Unfortunately, they don’t offer a demo account, just live accounts with a minimum deposit of 1$.

Get your money back from a scam

If you?ve been ripped off by scammers, get in touch and our team of experts will work to get your money back

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.