Demo 14: How to use MQTT and Arduino ESP32 to build a simple Smart home system

1. Introduction
- Currently, there are many IoT protocols such as: CoAP, MQTT, AMQP, … In this tutorial, I will introduce MQTT, one of the famous IoT protocols. This protocol is to control and transfer data between devices in an IoT network
Note: for MQTTS please refer Demo 30: How to use Arduino ESP32 MQTTS with MQTTS Mosquitto broker (TLS/SSL).
MQTT is stand for Message Queuing Telemetry Transport. It has some features:
+    Use Publish/Subscribe/Topic mechanism
+    Lightweight protocol
+    Small code footprint
+    Build on top of the TCP/IP protocol
+    Less network bandwidth.
- The principal of MQTT is traditional Client-Server model. In this model, there is one MQTT Server (also called Broker) and many MQTT Clients. The MQTT Clients always keep connection with MQTT Server. The role of MQTT Server (broker) is to filter and forward the messages to subscribed MQTT Clients. The communication between clients is based on Publish/Subscribe/Topic pattern in which:
+ Message: has a topic.
+ Publish: sending the messages to network.
+ Subscribe: listening messages that contain topic that the client is interested in.
+ Broker: coordinating the communication between publishers and subscribers.
- Topic is an utf-8 string and has one - many levels which is separated by splash "/". For example: "floor1/room1/temp": this topic has 3 levels, human readable and easy to understand (we have floor 1 and in room 1 with temperature sensor). You can refer:
- Beside that, there are other concept that you need to know:
*QoS (Quality of Service): this indicator perform the guaranty of message exchange between sender and receiver. There are 3 levels:
+ QoS 0 - at most once (this level is the fastest, but not reliable)
+ QoS 1 - at least once (this is the default mode)
+ QoS 2 - exactly once (this level is the most reliable, but slowest)
You can refer at: 
*Retained Messages:  broker will keep the sent message so that when there is new subscriber that subscribe the topic that matches the retained message then that message will be sent to that subscriber.
- Most of MQTT libraries define some standard methods such as:
+    Connect(): connect to MQTT server.
+    Disconnect(): disconnect from MQTT server.
+    Subscribe(): subscribe a topic with MQTT server.
+    UnSubscribe(): unsubscribe a topic with MQTT server
+    Publish(): client publish a topic to network.
- For demo, we create a simple smart home network that have 3 client nodes (Smart phone, WiFi MCU with temperature sensor, WiFi MCU with LED/bulb controller) and 1 server node as a broker (PC or Raspberry Pi). In our application, we want to use smart phone to monitor the temperature and control the LED/bulb on or off.  So we design the MQTT model like below:
Figure: MQTT model for simple smart home application
2. Hardware
- To implement the model above, I will collect Node2 and Node3 into one node and this node is our ESP32 with DHT22 sensor and LED (bulb). Finally, we have 2 nodes: SM node and ESP32 node. We re-use the hardware schematic of Demo 13: How to display temperature/humidity using Google Chart/Jquery and control LED through Arduino ESP32 Web Server. In this demo we do not use microSD so please ignore it.
- Connections:
Connect VCC and GND of DHT22 (VCC=3.3V) to VCC (Vcc=3.3V) and GND of ESP32.
[ESP32 IO15 - DHT22 DATA]
Figure: esp32 + dht22 + LED for MQTT smart home demo
3. Software
3.1 MQTT Client side

SM node: I will use an Android Smartphone with a MQTT client application (IoT MQTT Dashboard) that is available on Google Play. You can download it here:
ESP2 node: I will use a MQTT client library (Pubsubclient). You can download it here:
Then unzip the downloaded file and copy it to Arduino/libraries folder.
- This library supports some standard functions that are mentioned above. To use these function we create an instance PubSubClient client(wifiClient). Because MQTT is built on top of the TCP/IP protocol so the input of this constructor is a TCP WiFiClient object.
3.2 MQTT server side
- I will use a popular MQTT server called Mosquito. You can download and install it here:
- Windows user
After finishing, from command line just run this command to start mosquito server: "mosquitto"
-  Ubuntu user:
From command line type the command below: 
sudo apt-get install mosquitto mosquitto-clients
This will install mosquito as a service. You can check whether the service is start or not by using command line: 
sudo service --status-all 2>&1 | grep mosquitto
-  Other OS, just follow:
Note: when we install mosquito, it also install 2 client programs called "mosquitt_sub" and "mosquito_pub" that we can use for debugging. 
For example:
- To monitor all topic on network using:
mosquitto_sub -v -h broker_ip -p 1883 -t "#" (change broker_ip to mqtt server ip)
- To publish a topic (publish topic room1/temp with value 30) using:
mosquitto_pub -t 'room1/temp' -m 30
 3.3 Assign roles
We define topics: 
-  Topic1: smarthome/room1/bulb #value : value can take 0 or 1 means on/off the LED (bulb).
- Topic2: smarthome/room1/temperature #value : value can take float number to express temperature.
Example: smarthome/room1/temperature 30 
With these topics SM node can subscribe Topic2 and publish Topic1. ESP32 node can publish Topic2 and subscribe Topic1.
3.4 Steps to run the system
- Start the MQTT server (on Wins invoke it manually, on Linux it is a service so just check the service is started)
- From Terminal run this: mosquitto_sub -v -h broker_ip -p 1883 -t '#' for debugging. You will see all the messages on the network.
- Create an Arduino project and Save as esp32mqtt with code:

/* Here ESP32 will keep 2 roles: 
1/ read data from DHT11/DHT22 sensor
2/ control led on-off
So it willpublish temperature topic and scribe topic bulb on/off

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

/* change it with your ssid-password */
const char* ssid = "dd-wrt";
const char* password = "0000000000";
/* this is the IP of PC/raspberry where you installed MQTT Server 
on Wins use "ipconfig" 
on Linux use "ifconfig" to get its IP address */
const char* mqtt_server = "";

/* define DHT pins */
#define DHTPIN 14
#define DHTTYPE DHT22
float temperature = 0;

/* create an instance of PubSubClient client */
WiFiClient espClient;
PubSubClient client(espClient);

/*LED GPIO pin*/
const char led = 12;

/* topics */
#define TEMP_TOPIC    "smarthome/room1/temp"
#define LED_TOPIC     "smarthome/room1/led" /* 1=on, 0=off */

long lastMsg = 0;
char msg[20];

void receivedCallback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message received: ");

  Serial.print("payload: ");
  for (int i = 0; i < length; i++) {
  /* we got '1' -> on */
  if ((char)payload[0] == '1') {
    digitalWrite(led, HIGH); 
  } else {
    /* we got '0' -> on */
    digitalWrite(led, LOW);


void mqttconnect() {
  /* Loop until reconnected */
  while (!client.connected()) {
    Serial.print("MQTT connecting ...");
    /* client ID */
    String clientId = "ESP32Client";
    /* connect now */
    if (client.connect(clientId.c_str())) {
      /* subscribe topic with default QoS 0*/
    } else {
      Serial.print("failed, status code =");
      Serial.println("try again in 5 seconds");
      /* Wait 5 seconds before retrying */

void setup() {
  // We start by connecting to a WiFi network
  Serial.print("Connecting to ");

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
  /* set led as output to control led on-off */
  pinMode(led, OUTPUT);

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

  /* configure the MQTT server with IPaddress and port */
  client.setServer(mqtt_server, 1883);
  /* this receivedCallback function will be invoked 
  when client received subscribed topic */
  /*start DHT sensor */
void loop() {
  /* if client was disconnected then try to reconnect again */
  if (!client.connected()) {
  /* this function will listen for incomming 
  subscribed topic-process-invoke receivedCallback */
  /* we measure temperature every 3 secs
  we count until 3 secs reached to avoid blocking program if using delay()*/
  long now = millis();
  if (now - lastMsg > 3000) {
    lastMsg = now;
    /* read DHT11/DHT22 sensor and convert to string */
    temperature = dht.readTemperature();
    if (!isnan(temperature)) {
      snprintf (msg, 20, "%lf", temperature);
      /* publish the message */
      client.publish(TEMP_TOPIC, msg);
- From Android smart phone, open IoT MQTT Dashboard) and follow steps below to set up it a MQTT client:
Figure: Configure MQTT Server that it will connect to
Figure: After configuring server, choose it 
Figure: Choose Subscribe tab and create topic temp
 Figure: Choose Publish tab to create a Switch for toogling LED
 Figure: Fill topic led for Switch
Figure: After finishing, here is the GUI for Publish tab, one Switch
 Figure: You can see smart phone received temp topic 
4. Result 

Post a Comment


Anonymous said…
I appreciate your tutorial, yet there are some mistakes that should be clarified, the most obvious being your statement:
"Topic: the message that is transferred on network"
A topic by far is not a message itself but rather a category for a message.
The client is never sending topics but sending messages that have a / a classified for a specific topic.
You should possibly consider a topic string as part of a message object from a sending client perspective.
Thank you very much, I updated it. I just want to express it in a general way so that users are easy to understand. :)
Jvision Apps said…
good effort...!very useful
UbiBot said…
IOT Based products changed the world. I would like to share this informative article with team.
daizy mathew said…
Thanks for sharing this useful information.
python training in chennai
divi said…
Hi, Thanks for the great information and it is very useful to read your blog with easily understand for all readers. Well done!
web design company in velachery
It’s interesting content and Great work....Sarkari Job are an attraction to a huge Indian population. Whenever one looks for a settled future, we tend to look at SSC Jobs, Railway Jobs, Bank Jobs, Defence Jobs and Civil Service Jobs.
Hey, Are you looking for the best python training in Jaipur ,so grab this opportunity . DZONE is here for you with the best online and offline Classes ,Techniques and Experiences .Join us to improve your skills and Better Future
To book free demo session, feel free to call us at 8432830240 or 0141-4108506.
One of the greatest benefits of digital marketing is that it allows you to target your ideal buyers.
We Provide complete digital marketing course in 3 months.
include in this course: SEO, SEM,GOOGLE ADS,Email Marketing, Web Development etc.
✔️100% Best knowledge
✔️professional and experienced
✔️practical training
✔️100% certification after the complete cours
✔️Online Classes are available
DZone Internship/Training 2020
Are you searching for Python | Machine Learning | Data Science | Tableau | Java | Android | P.H.P | Digital Marketing Internship in Jaipur? Join our project based Job-Oriented online/offline Training under expert guidance. Hurry!! 50% discount available on all Courses. To Avail this Opportunity Reserve Your Seats Now !! ENROLL NOW!! To book free demo session, feel free to call us at 8432830240 or 0141-4108506..
subha said…
Great efforts put to find the list of articles that are very useful to know. I’m thoroughly enjoying your blog. And Good comments create relations. You’re doing great work. Keep it up. thanks
Ai & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
Mark Cybert said…
I liked your video. And even buy youtube likes from this site for you
Ashok said…
This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea.

data science course in India
technology said…
If you have the proficiency in these fields, you will have an added advantage over other professionals. Once you become an expert, you can demand a higher pay. data science course syllabus
I am glad to post a worthy article about the German Language Course and IELTS Coaching from KCR consultants, this may change your career growth and language skill.
KCR-German Language
technology said…
How could that person be true to the values and the brand of the company, which the chief executive has spent so much time, energy and money developing? Salesforce interview questions
Aishwariya said…
Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
Primavera p6 Training Online | Primavera Training Chennai
pgslot ซึ่งเกมคาสิโนออนไลน์เกมนี้เป็นเกมที่เรียกว่าเกม สล็อตเอ็กซ์โอ คุณรู้จักเกมส์เอ็กซ์โอหรือไม่ 90% ต้องรู้จักเกมส์เอ็กซ์โออย่างแน่นอนเพราะในตอนนี้เด็กนั้นเราทุกคนมักที่จะเอาก็ได้ขึ้นมา สล็อต เล่นเกมส์เอ็กซ์โอกับเพื่อนเพื่อนแล้วคุณรู้หรือไม่ว่าในปัจจุบันนี้เกมส์เอ็กซ์โอนั้นกลายมาเป็นเกมซะลอสออนไลน์ที่ให้บริการด้วยเว็บคาสิโนออนไลน์คุณสามารถเดิมพันเกมส์เอ็กซ์โอกับเว็บคาสิโนออนไลน์ได้โดยที่จะทำให้คุณนั้นสามารถสร้างกำไรจากการเล่นเกมส์เดิมพันออนไลน์ได้เราแนะนำเกมส์ชนิดนี้ให้คุณได้รู้จักก็เพราะว่าเชื่อว่าทุก

Jon Rarine said…
This article was quite interesting to read. I’d want to express my gratitude for the time and attention you put into making this fantastic post. Enterprises may use our industrial IoT platform to create unique IoT applications. UbiBot create, deploy, and support an industrial IoT platform that enables you to create custom industrial IoT applications for your business. Our IoT platform is only offered to manufacturers and government agencies working on smart city projects.

Your post is exactly what I was looking for. There are a few existing solutions for smart homes on the market such as the Xiaomi smart home set, for example. Arduino has a lot of pros for its flexibility. Many posts on Instagram talk about it, look for the ones that have dozens of likes and comments on. By the way, you can get the same numbers on any post by simply following to They got an ultimate set of tips on how to win more eyes for your posts on IG devoted to smart homes.
Jobi Johnson said…
Thanks for posting this info. I just want to let you know that I just check out your site. Blade Runner 2049 Coat
John P. Ketchum said…
We help private individuals top security companies in London
and companies all over the UK with a wide range of complex assignments requiring specialist services to securely and safely deliver or protect their assets.
fantasy expert 11 Cricket Fantasy League with Best play Fantasy Cricket App Play Cricket earn Money. Download App to know more Play and win Exclusive Prizes & Experiences only with Fantasy Power 11.Instant Paytm Withdrawal Fantasy Power 11 Fantasy Cricket Best App
Great post I would like to thank you for the effort you put into writing this interesting and informative article, no matter what is the purpose of your trip to Turkey, you need to pay the visa cost Turkey before submitting the visa application .Depending on your desired option, the e Visa Turkey cost are calculated.
What Should I Do To Resolve Cash App Won't Let Me Send Money Issue?
Do you know what you would do if Cash App Won't Let Me Send Money? In such a case, you will need to share your problems and hurdles permanently from the root. All you have to do is to take necessary suggestions and troubleshooting assistance to get rid of such problems within the least time frame.
Great info.. Thank you If you are transiting through Kenya to your destination, then you can apply online for Kenya transit visa through online Kenya e vias application
This is a topic that’s near to my heart… Many thanks!!! Indian visa online for US citizens, US citizens are eligible to apply for the Indian eVisa. The process is completely online and there is no need to submit the paperwork in person to any Indian Embassy or Consulate.
우리카지노 said…
Your explanation is organized very easy to understand!!! I understood at once. Could you please post about 우리카지노?? Please!!

eddielydon said…
I like the way you express information to us. Thanks for such post and please keep it up. Just Love You Hoodie
mrbobystone said…
I love to recommend you Where can crawl Exciting Products latest Jackets, Coats and Vests Click Here Attack on Titan Cloak
Real Jackets said…
among us jacketsHey there exceptional blog! Does running a blog like this take a massive amount work?
I’ve no expertise in computer programming however I was hoping to start my own blog in the near
future. Anyway, should you have any ideas or techniques for new
blog owners please share. I know this is off topic but I just needed to ask.
Real Jackets said…
Have you ever considered writing an ebook or guest authoring on other blogs?
I have a blog based on the same ideas you discuss and would really like to have
you share some stories/information. I know my visitors would value your work. lakers jackets
If you are even remotely interested, feel free to shoot me an e
The emergency visa on arrival is also a visa. As such, your urgent visa will be stamped in one of the airports that you use in India.

George Mark said…
Thanks for this. This is the simplest explanation I can understand given the tons of Explanation here. Ferris Bueller Leather Jacket
Sarah Josave said…
Thank you for sharing this fantastic article. This article has made me very happy. Brown leather Jacket
Hello sir, This is a fantastic article you've written, keep it up, You know Myanmar visa online service has been resumed from 1st April 2022 for business visa applications. You can get more info about Myanmar eVisa fee via our Myanmar evisa page.

Hello everyone, Many people ask, How to apply Indian e visa? You can read about applying for an Indian e visa eta through our website.
Rajan Mhatre said…
Thanks for one marvelous posting! I really enjoyed reading it, you might be a great author. I will be sure to bookmark your blog and will eventually come back later on.
Get connected with us, If you are looking for customised reversible raincoat.
Who does not want to look noticeable at a party with some Best Kevin Costner Yellowstone Jackets incredible fashion sense? Of course, we all do. But don’t you think that going with the option of outdoor shopping in this digital era is a hectic task to do? What if we provide you with a great solution for this? A place in which you can trust blindly and shop for outstanding quality products. We are here with the best website in the town and this time we have got a list of the best of Kevin Costner Yellowstone Outfits from the series Yellowstone.
DAVE said…
Much obliged alot for this useful blog. You folks are astounding and the substance you giving is simply awe-inspiring. Likewise look at
keniazugei said…
This is a really decent site post. Not very numerous individuals would really, the way you simply did. I am truly inspired that there is such a great amount of data about this subject have been revealed and you’ve put worth a valiant effort with so much class. Cassian Blue Wax Jacket Outfits.
cristinajohn said…
I won’t think twice to endorse your blog post to anybody who wants and needs support in this I went over this article. It is quite happy to see this.I’m really grateful for thisarea.Sons Of Anarchy Vest
james willam said…
It is possible to Getting an Argentina visa through embassy or consulate if you cannot receive an Electronic Travel Authorization (ETA). The following steps will help you apply for an Argentina visa at the embassy: Check the visa requirements, Gather the required documents, Schedule an appointment, Submit your application, Wait for processing, Collect your visa.

zarkazijar said…
Thank you for letting us know about university postgraduate admission form . Visit Best Rated Educational Update Portal in the World; Examination and Academic Guide, High Paying Jobs & Scholarship Websites.

Thanks for sharing this valuable information with us.
Gothic clothing
henryisabella said…
If you're planning a trip to Lesotho, it's essential to know how to Apply for Lesotho Visa. The process of obtaining a Lesotho visa may vary depending on your country of citizenship and the purpose of your visit. Generally, you'll need to submit an application, passport photos, a valid passport, and other required documents.
Anonymous said…
Awesome! I was just looking for something like this article for this topic. I just loved it! black leather jacket men
darknet hitman said…
I feel that everyone will profit from this website in some way. Please contribute to this worthy cause.
real life hitman
Anonymous said…
Great article! I appreciate the valuable insights you shared, if you are looking for a latest games then you can visit this site: going balls mod apk

Emma watson said…
What I appreciate most about this Goku Drip Black Puffer Jacket is its versatility. I can wear it casually with jeans or dress it up for a more streetwear-inspired look. It's definitely a conversation starter, and I've made some new friends just because they recognized the Goku reference!
Emily said…
The jacket's exterior is crafted from high-quality, water-resistant material, ensuring that you stay warm and dry in various weather conditions. Its puffer design, filled with premium insulation, provides excellent heat retention, making it ideal for chilly days or winter adventures. Goku Drip Puffer Jacket
Anonymous said…
If you're planning a trip to Lesotho, it's essential to know how to Apply for Lesotho Visa. The process of obtaining a Lesotho visa may vary depending on your country of citizenship and the purpose of your visit. Generally, visityou'll need to submit an application, passport photos, a valid passport, and other required documents.
ethan said…
If you're planning a trip to Lesotho, it's essential to know how to Apply for Lesotho Visa. The process of obtaining a Lesotho visa may vary depending on your country of citizenship and the purpose of your visit. Generally, to visit you'll need to submit an application, passport photos, a valid passport, and other required documents.
Emily said…
The Kate Upton Astros Sweater is a stylish and unique piece of sports-inspired fashion that effortlessly blends comfort with team spirit.
Hii everyone, Exploring Turkey's Average Cost of Living Expenses in 2023 provides insights into the economic landscape. Analyzing factors such as housing, food, and transportation illuminates the financial requirements for residents and expatriates.
Anonymous said…
Real estate agent websites with integrated IDX (Internet Data Exchange) and CRM (Customer Relationship Management) systems are essential tools for real estate professionals. These websites allow agents to showcase property listings, capture leads, and efficiently manage client relationships. Here are key features and considerations for creating real estate agent websites with IDX and CRM integration.
real estate agent websites with idx and crm
Edison hope said…
Hii everyone, Navigating international travel requires understanding visa procedures. The Azerbaijan visa process simplifies entry into this captivating country. Learn about the streamlined steps and requirements for a smooth journey to Azerbaijan.
Maria3400 said…
Fantastic post! Insightful content that leaves me eager for more. Keep up the great work! For a seamless visit to Azerbaijan, familiarize yourself with Azerbaijan e visa requirements. Ensure your passport validity, complete the online application, and provide necessary documents for a smooth application process.
Hello! I wanted to express my gratitude for the valuable information shared on your blog. Your dedication to providing in-depth insights is truly commendable. Saudi Arabia Visa on Arrival: Explore the Kingdom hassle-free! Discover the eligibility criteria, duration, and essential documents required for a smooth entry into this diverse and historic nation. Plan your trip today!
William said…
The evisa gov Azerbaijan portal is your essential online resource for securing a visa to explore the captivating wonders of Azerbaijan. Designed to simplify the visa application process, this user-friendly website offers a convenient and efficient way for travelers to obtain their e-Visas. Whether you're planning to immerse yourself in the vibrant culture of Baku, venture into the scenic landscapes of the Guba region, or discover Azerbaijan's rich history, the evisa gov Azerbaijan platform ensures a hassle-free start to your journey. In this guide, we'll walk you through the steps and requirements for using the evisa gov Azerbaijan website to obtain your travel authorization, so you can embark on your Azerbaijani adventure with ease.
jofra archer said…
"Your dedication to sharing valuable information is truly admirable. Thank you for your insightful content!" Tanzanian citizens can obtain an Indian visa for tourism, business, or medical purposes. India Visa for Tanzania Citizens. The application process is available online or at authorized centers. Ensure all necessary documents are ready, pay the fees, and follow processing guidelines, which may vary. Check eligibility before applying and look forward to your visit to India!
Edison hope said…
Hello everyone, UK visa tracking from India is a straightforward and essential step in ensuring a smooth travel experience. This guide will assist you in easily monitoring your visa application status, keeping you informed and prepared for your journey. Additionally, if you're looking for information about tracking a UK visa from India, we can provide assistance with that process as well.
Your blog is a testament to the art of meaningful storytelling. The way you craft narratives and infuse them with valuable lessons is truly commendable. It's evident that you invest time and passion into creating content that resonates with readers on both an intellectual and emotional level.
Admin said…
Nice Blog admin, Keep visiting KGO Multi Space to download and use durable accounts at any time.
HD Streamz said…
Great article admin
snapptube said…
This comment has been removed by the author.
What as up, I read your blogs like every week. Your writing style is awesome, keep up the good work!
Apache Spark Training
SAP Spartacus Training
<a href=">Linux Admin Training</a>
Your styling blogs saved many of my occasions. Thank you for updating us with good-quality content. Black Friday deals
rts tv said…
Nice Blog admin, Keep visiting Rts tv to download and use durable accounts at any time
medlr said…
This is a very interest blog.. I really like this blog... visit here for buy medicine online with us
ccompare medicine price online
online pharmacy comparison
Yashvi Thareja said…
This is a really fascinating and interesting blog.Thank you for updating withe the quality content. If you are keen to attain the knowledge onProcess Support Services. TresVista can ensure the efficiency and accuracy in diverse processes.
Singhal said…
Hi! this is nice article you shared with great information. if you guys are looking for volvo bus booking you can visit PML Holidays
Singhal said…
Thank you for the article, if you guys are looking for holiday tour packages you can visit PML Holidays.
Anonymous said…
This is a very interest blog.. I really like this blog... visit here for English Spoken Classes Prayagraj