Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
97 views16 pages

Control ESP32 with MQTT Protocol

Practical Work 5 DEC50132 INTERNET BASED CONTROLLER POLITEKNIK SEBERANG PERAI (PSP)

Uploaded by

JustShareIt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
97 views16 pages

Control ESP32 with MQTT Protocol

Practical Work 5 DEC50132 INTERNET BASED CONTROLLER POLITEKNIK SEBERANG PERAI (PSP)

Uploaded by

JustShareIt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 16

Department of Electrical Engineering

DEC50132 – Internet Based Controller


PRACTICAL WORK NO : 5
TITLE : Message Queuing Telemetry Transport (MQTT) -
Controlling ESP32 output using MQTT.
DATE :
LECTURER’S NAME :

PRACTICAL SKILL ASSESSMENT ATTAINMENT LAB REPORT ATTAINMENT


[CLO2, PLO5, P4] ASSESSMENT
S1 
Able to understand the node S2  
without supervision S3  Result
S4 
S1 
Able to establish connection to S2  Discussion 
the broker from MQTTbox/ IOT
S3 
MQTT panel to LED
S4 
S1 
Able to deploy the node-red , S2  Conclusion 
broker and control LED
S3 
S4 
S1 
S2 
Able to get the PBL output Score (30)
S3 
S4 
S1
Percentage
S2 (30%)
Score (40)
S3
S1
S4 S2
Total CA Marks
S1 (100%) S3
S2
Percentage (70%)
S3
S4
S4

BIL. GROUP MEMBERS REGISTRATION NO.


S1
S2

JKE PSP
PRACTICAL SKILL RUBRIC

Description Mark Scale Attainment

Student can complete all tasks assigned WITHOUT errors 5 x2 10

Student can complete all tasks assigned with A FEW errors 4 x2 8

Student can complete all tasks assigned with MORE errors 3 x2 6

Student can complete partial tasks assigned WITHOUT errors 2 x2 4

Student can complete partial tasks assigned with A FEW errors 1 x2 2

Student shows no response/task not attempted 0 x2 0

DATA ACQUISITION AND COMMUNICATION RUBRIC

Excellent Very Good Good Fair Unsatisfactory


Report Component
(PLO2,LD2)
5 4 3 2 1

Results Professional looking Accurate Accurate Incomplete result, Data are not
and accurate representatio representations of the major mistakes. shown OR are
• Results in the form representation of the n of the data data in written form, inaccurate.
of data, data in tables and/or in tables but no graphs or
calculation, graphs. Graphs and and/or tables are presented.
waveform, graph tables are labelled and graphs.
etc. titled.

Analysis/ Discussion All point of discussion Most points Some points of Some points of Very few points
on the results obtained of discussion discussion on results discussion on of discussion, not
• Ability to present, covered and on results obtained covered and results obtained properly
interpret and elaborated. obtained elaborated. covered and but elaborated.
analyse result. covered and not properly
elaborated. elaborated.

Conclusion Conclusion includes The closing The closing paragraph The closing No conclusion
• Provide answers to whether the findings paragraph attempts to paragraph do not was included in
supported the summarizes summarize but draws attempts to the report.
objectives stated hypothesis, possible and draws a a weak conclusion. summarize the
sources of error, and sufficient experiment OR
earlier. what was learned from conclusion. shows little effort
• Ability to learn the experiment. and reflection.
something from the
experiment.

JKE PSP
Practical Work 5

Title: Message Queuing Telemetry Transport (MQTT) -Controlling ESP32 output using
MQTT.

Objectives:

Upon completion of this practical work, students should be able to:

• Write code to established internet connection (MQTT Client)


• Write code to publish and subscribe MQTT
• Apply writing simple IoT application for controlling LEDs and monitoring sensor reading
with Node-Red dashboard

Equipments:

1. PC installed with Node.js, MQTTbox


2. Android phone with IOT MQTTPanel apps.
3. Internet connection (Access Point dedicated to the Laboratory)
4. ESP32 board.

Theory:

MQTT is one of the most commonly used protocols in IoT projects. It stands for Message Queuing
Telemetry Transport.

In addition, it is designed as a lightweight messaging protocol that uses publish/subscribe


operations to exchange data between clients and the server. Furthermore, its small size, low
power usage, minimized data packets and ease of implementation make the protocol ideal of the
“machine-to-machine” or “Internet of Things” world.

JKE PSP
How do these devices communicate with each other?
Certainly, web browsers use HTTP protocol to communicate with the servers on the internet.
Likewise, IoT devices use specific protocols to communicate (send and receive data) over the
internet to each other.
And here are some of the most known IoT protocols:

• CoAP (Constrained Application Protocol)


• AMQP (Advanced Message Queuing Protocol)
• DDS (Data Distribution Service)
• STOMP (Simple Text Oriented Messaging Protocol)
• MQTT (Message Queue Telemetry Transport)

The last one is the most used protocol in IoT projects. That’s due to it’s fast, lightweight and easy
to implement.

Why MQTT?
MQTT has unique features you can hardly find in other protocols, like:

It’s a lightweight protocol. So, it’s easy to implement in software and fast in data transmission.
It’s based on a messaging technique. Of course, you know how fast your messenger/WhatsApp
message delivery is. Likewise, the MQTT protocol.
Minimized data packets. Hence, low network usage.
Low power usage. As a result, it saves the connected device’s battery.
It’s real time! That’s is specifically what makes it perfect for IoT applications.

How MQTT works

Like any other internet protocol, MQTT is based on clients and a server. Likewise, the server is
the guy who is responsible for handling the client’s requests of receiving or sending data between
each other.

MQTT server is called a broker and the clients are simply the connected devices.
So:

When a device (a client) wants to send data to the broker, we call this operation a “publish”.
When a device (a client) wants to receive data from the broker, we call this operation a
“subscribe”.

In addition, These clients are publishing and subscribing to topics. So, the broker here is the one
that handles the publishing/subscribing actions to the target topics.

JKE PSP
Example:
Let’s say there is a device that has a temperature sensor. Certainly, it wants to send his readings
to the broker.

On the other side, a phone/desktop application wants to receive this temperature value.
Therefore, 2 things will happen:

The device defines the topic it wants to publish on, ex: “temp”. Then, it publishes the message
“temperature value”.

The phone/desktop application subscribes to the topic “temp”. Then, it receives the message that
the device has published, which is the temperature value.

Again, the broker role here is to take the message “temperature value” and deliver it to
phone/desktop application.

MQTT Components:
That takes us to the MQTT components, which are 5 as follows:

Broker, which is the server that handles the data transmission between the clients.
A topic, which is the place a device wants to put or retrieve a message to/from.
The message, which is the data that a device receives “when subscribing” from a topic or send
“when publishing” to a topic.
Publish, is the process a device does to send its message to the broker.
Subscribe, where a device does to retrieve a message from the broker.

JKE PSP
How many devices you can connect to a broker
The number of connected devices “clients” to the broker depends on the broker service provider.
In fact, it can reach a massive number of clients those are publishing and subscribing all the time.
but the amazing part of this isn’t only the huge number of these connected devices but also any
the fact that any device can get any other device’s data at any time. As a result, the applications
based on these quickly shared data are limitless.

Why not HTTP

HTTP is slower, more overhead and power consuming protocol than MQTT. So, let’s get into each
one separately:
• Slower: because it uses bigger data packets to communicate with the server.
• Overhead: HTTP request opens and closes the connection at each request, while MQTT stays
online to make the channel always open between the broker “server” and clients.
• Power consuming: since it takes a longer time and more data packets, therefore it uses much
power.

Additional notes

The difference to HTTP is that a client doesn’t have to pull the information it needs, but the broker
pushes the information to the client, in the case there is something new. Therefore each MQTT
client has a permanently open TCP connection to the broker. If this connection is interrupted by
any circumstances, the MQTT broker can buffer all messages and send them to the client when it
is back online. As mentioned before the central concept in MQTT to dispatch messages
are topics. A topic is a simple string that can have more hierarchy levels, which are separated by a
slash. A sample topic for sending temperature data of the living room could be house/living-
room/temperature. On one hand the client can subscribe to the exact topic or on the other hand
use a wildcard. The subscription to house/+/temperature would result in all message send to the
previously mention topic house/living-room/temperature as well as any topic with an arbitrary
value in the place of living room, for example house/kitchen/temperature. The plus sign is a single
level wild card and only allows arbitrary values for one hierarchy. If you need to subscribe to more
than one level, for example to the entire subtree, there is also a multilevel wildcard (#). It allows to
subscribe to all underlying hierarchy levels. For example house/# is subscribing to all topics
beginning with house.

JKE PSP
Which broker to use?
There are many brokers that implement the MQTT protocol.

• Bevywise MQTTRoute
• Mosquito
• HiveMQ

Procedures:

A. Node-red platform

1. Refer practical work 3 for installation. Run Node-js application.

2. Open cmd-prompt and type node-red

3. On your browser type : localhost:1880

4. Join the node as shown below

JKE PSP
1. MQTT in
node
3. debug node

4. Button node
2. MQTT in
node
5. Button node

5. set the MQTT in object numbered by 1and 2 as shown below:

Use your topic

JKE PSP
Edit the server

6. set the debug object number 3 as shown below:

7. set the ON button as shown below:

JKE PSP
Use your topic

8. Set the OFF button as show below:

JKE PSP
9. Then, DEPLOY the node.

10. Launch the node-red dashboard, and the interface will be shown below:

JKE PSP
ESP32 and Node-red connection

1. Open your Arduino IDE.


2. Write the given code:

//intan shafinaz abd razak 20.02.2020

#include<PubSubClient.h> //download https://github.com/knolleary/pubsubclient

#include <WiFi.h>

const char* mqtt_server="broker.hivemq.com";

WiFiClient espClient;

PubSubClient client(espClient);

const int ledPin = 22; //pin at ESP32

void setup() {

pinMode(ledPin,OUTPUT);

Serial.begin(115200);

Serial.print("connecting");

WiFi.begin("zzzzzzzzzi","xxxxxxxl"); //SSID,PASSWORD

client.setServer(mqtt_server, 1883);

client.setCallback(callback);

JKE PSP
while(WiFi.status()!=WL_CONNECTED){

delay(500);

Serial.print(".");

Serial.println();

reconnect();

void callback(char* topic,byte* payload,unsigned int length1){

Serial.print("payload arrived[");

Serial.print(topic);

Serial.println("]");

String payloadTemp;

for(int i=0;i<length1;i++){

Serial.print((char)payload[i]);

payloadTemp += (char)payload[i];

if (String(topic) == "XXXXXXXXXXXX") { //use your own topic

Serial.print("Changing output to ");

if(payloadTemp == "on"){

Serial.println("on");

digitalWrite(ledPin, HIGH);

JKE PSP
else if(payloadTemp == "off"){

Serial.println("off");

digitalWrite(ledPin, LOW);

Serial.println();

void reconnect(){

while(WiFi.status()!=WL_CONNECTED){

delay(500);

Serial.print(".");

while(!client.connected()){

if(client.connect("ESP8266Client123456789")){

Serial.println("connected");

client.subscribe("XXXXXXXXXXXXXXX"); //SUBCRIBE TO MQTT BROKER

else{

Serial.print("failed,rc=");

Serial.println(client.state());

Serial.println(" try again in 5 seconds");

// Wait 5 seconds before retrying

delay(5000);

JKE PSP
void loop() {

if(!client.connected()){

reconnect();

client.loop();

*** download pubsubclient here: https://github.com/knolleary/pubsubclient

3. Upload in your ESP32 Board (make sure you have connected your LED)

4. By using button in node red dashboard, you will get the serial monitor as shown below:

5. When ON button is pressed, LED will be turned ON and vice versa.

JKE PSP
Problem Based Learning

Based on all the steps above, use your understanding to get the output in your node-red
dashboard and Android or IOS IOT MQTT Panel to control two LEDs at dining hall and kitchen in
your house.

Discussion:

Write your discussion based on practical activity and PBL. Explain the step how you get the
results.

Conclusion:

Write your conclusion on this practical work.

References
https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/

http://www.iotsharing.com/2017/05/how-to-use-mqtt-to-build-smart-home-arduino-esp32.html

JKE PSP

You might also like