Professional Documents
Culture Documents
Lab 02 - MQTT - NODEMCU-2
Lab 02 - MQTT - NODEMCU-2
Learning Outcomes:
• Understand the fundamentals of MQTT protocol including topics, subscriptions, and messaging.
• Implement a NodeMCU client that can publish to and subscribe from MQTT topics.
• Use MQTTx client to simulate an IoT device or application, interacting with the MQTT broker.
• Analyze and troubleshoot common issues in MQTT communications to ensure reliable data
exchange.
• In the Additional Board Manager URLs field, enter the following URL:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
• In the Boards Manager, type "ESP8266" into the search bar, find the ESP8266 by ESP8266
Community, and click "Install".
• Windows: Most ESP8266 modules use a CH340 or CP2102 USB-to-serial chip that might require
drivers.
• Download the driver for CP2102 depending on your module. These are available on the
Silicon Labs website, which provides drivers for Windows, macOS, and Linux. Here's the
link: https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers
• Check your device manager to check which com port is being used for the ESP8266.
• Plug your ESP8266 module into your computer using the USB data cable.
• Select the correct board by going to Tools > Board and choosing your specific ESP8266 module
(e.g., NodeMCU 1.0).
• Windows: Go to Tools > Port and select the COM port associated with the ESP8266
(usually denoted as COM3, COM4, etc.).
• This will blink the builtin Led on your board. The verifies that board is connected and working
• Upload this code to your ESP8266 and open the Serial Monitor to check the output. It should
list all available WiFi networks. If no networks are listed, there may be an issue with the WiFi
module or its configuration. Make sure baud rate is the same in serial monitor as put in the code
(e.g 115200)
• Once Wifi scanning is done, select your Wifi and run the below code to verify Wifi Connectivity.
#include <ESP8266WiFi.h>
void setup() {
Serial.begin(115200);
WiFi.begin("YOUR_SSID", "YOUR_PASSWORD");
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// Keep loop empty.
}
• Replace "YOUR_SSID" and "YOUR_PASSWORD" with your actual WiFi credentials. This
script attempts to connect to your WiFi and prints the IP address upon successful
connection.
• Ensure the board is disconnected from power when making hardware changes.
This guideline provides a foundational path for students to start experimenting with the ESP8266 in a lab
setting, from installation to running their first program. Each step is crucial for understanding and
successfully using the ESP8266 in various projects.
With the NodeMCU configured and connected to the internet, the second part of the lab transitions to
the core topic of MQTT communication. Here, students will implement and test MQTT-based messaging
using the NodeMCU as an MQTT client and the EMQX broker to facilitate message passing. MQTTx, a
cross-platform MQTT desktop client, will be used to simulate another client in the MQTT system, allowing
students to explore both publishing and subscribing functionalities. This part emphasizes understanding
MQTT's lightweight messaging protocol, which is pivotal for IoT environments where low power usage
and network bandwidth are key considerations.
Prerequisites
• Internet connection
Copy and paste the code provided below into a new sketch in the Arduino IDE. This is a basic MQTT
example where your ESP8266 will connect to an MQTT broker, Publish a message for a specific topic,
and listen for messages on the same topic. For this code to work, the library (PubSubClient.h) needs to
be installed. Install the library in Arduino IDE by going to Tools>Manage libraries. Search for this library
(PubSubClient by Nick O’Leary), and click install.
• You can change your topic to what you want to publish or subscribe to.
• Mqtt_broker can be selected as per requirements. Here the MQTT broker is “broker.emqx.io”
• Connect your ESP8266 module to your computer using the USB cable.
• In the Arduino IDE, select the correct board and port under Tools > Board and Tools > Port.
• Click the Upload button to compile and upload the sketch to your ESP8266.
• Open the Serial Monitor from the Arduino IDE (magnifying glass icon in the top right corner).
• Set the baud rate to 115200 (bottom right of the Serial Monitor window).
• Observe the outputs as your ESP8266 connects to WiFi and the MQTT broker, and listens for
messages.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// WiFi
const char *ssid ="Your WIFI SSID"; // Enter your WiFi name
const char *password ="WIFI PSWD"; // Enter WiFi password
// MQTT Broker
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "esp8266/HZ";
const char *mqtt_username = "emqx";
const char *mqtt_password = "public";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
void loop() {
client.loop();
}
The ESP8266 setup includes configuring WiFi credentials, connecting to the MQTT broker, and setting up
a callback function that reacts to received MQTT messages by controlling the LED. This task effectively
demonstrates the integration of simple IoT control mechanisms using MQTT, a lightweight messaging
protocol, making it a practical example of remote device management and real-time state control in
embedded systems.
• Hardware: Use an ESP8266 module, which has built-in WiFi capabilities and sufficient GPIO pins
for simple control tasks such as LED management.
• Software: Program the ESP8266 using the Arduino IDE, which supports the ESP8266 board after
adding the necessary board manager URL.
• Configure the ESP8266 to connect to a local WiFi network by providing the SSID and password.
This step is crucial for enabling the ESP8266 to access the internet and communicate with the
MQTT broker.
• Set up the MQTT client on the ESP8266 to connect to broker.emqx.io. Use MQTT credentials if
required by the broker for authentication.
• Implement a reconnection strategy to ensure the ESP8266 remains connected to the MQTT
broker or attempts to reconnect if the connection is lost.
• Define a callback function that triggers whenever a message is received on the subscribed topic.
This function checks the content of the message and controls the LED accordingly.
• Use simple string comparisons within the callback to determine whether the LED should be turned
on or off based on the messages "LED ON" or "LED OFF".
• Publish messages to the MQTT topic (e.g esp8266/HZ) using an external MQTT client (e.g., MQTTx)
to test if the LED on the ESP8266 responds appropriately to the commands.
• Monitor the ESP8266's serial output to debug and confirm that it receives the correct commands
and that the LED's state changes as expected.
Code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// WiFi
const char *ssid ="PRJ"; // Enter your WiFi name
const char *password ="PRJ2017@"; // Enter WiFi password
// MQTT Broker
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "esp8266/HZ";
const char *mqtt_username = "emqx";
const char *mqtt_password = "public";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// Set software serial baud to 115200;
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
// connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println();
Serial.println("-----------------------");
void loop() {
client.loop();
}
Hardware Required:
ESP8266 module
Servo motor
External power supply for the servo (recommended if the servo requires more than 5V or if it draws
significant current)
Circuit Setup:
Signal Pin: Connect the servo's control (signal) wire (usually orange or yellow) to a GPIO pin on the
ESP8266 that supports PWM. Common choices are GPIO12, GPIO13, or GPIO14.
Power and Ground: Connect the power (red) and ground (brown or black) wires of the servo directly
to an external power supply. If your servo operates at 5V and doesn’t draw much current, you can
connect it to the 5V and GND pins of the ESP8266.
Software Setup:
Use the Arduino IDE with the ESP8266 board definitions installed.
Write a script to connect the ESP8266 to WiFi, connect to an MQTT broker, subscribe to a topic, and
use messages from this topic to set the angle of the servo.
Code Overview:
Understand the basics of PWM (Pulse Width Modulation) in controlling servo motors.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
// WiFi
const char *ssid = "PRJ"; // Enter your WiFi name
const char *password = "PRJ2017@"; // Enter WiFi password
// MQTT Broker
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "esp8266/HZ";
const char *mqtt_username = "emqx";
const char *mqtt_password = "public";
const int mqtt_port = 1883;
void setup() {
// Set software serial baud to 115200;
Serial.begin(115200);
myServo.attach(D1); // Attach servo to pin D1
void loop() {
client.loop();
}
• Open MQTTx and connect to the EMQX broker using the broker address broker.emqx.io, and
username and password specified in your ESP8266 code.
• Power up your ESP8266 and ensure it connects to WiFi and the MQTT broker.
• Use MQTTx to send control messages and observe the LED and motor responding to your
commands.
Hardware Required:
• ESP8266 module
• LED
Circuit Setup:
• Other End of Resistor: Connect to any GPIO pin on the ESP8266 (common choices are
GPIO2 or GPIO16).
• Cathode (Shorter Leg): Connect directly to one of the GND pins on the ESP8266.
• Write a script to connect to WiFi, connect to an MQTT broker, subscribe to a topic, and
control the state of the LED based on the messages received (e.g., "ON" or "OFF").
Code Overview:
• Commands like "ON" and "OFF" control the state of the LED.
• Open MQTTx and connect to the EMQX broker using the broker address broker.emqx.io, and
username and password specified in your ESP8266 code.
• Power up your ESP8266 and ensure it connects to WiFi and the MQTT broker.
• Use MQTTx to send control messages and observe the LED and motor responding to your
commands.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// WiFi credentials
const char *ssid = "PRJ"; // Enter your WiFi name
const char *password = "PRJ2017@"; // Enter WiFi password
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
digitalWrite(ledPin, LOW); // Ensure LED is off when starting up
Serial.begin(115200);
// connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
Serial.println(WiFi.status());
}
Serial.println("Connected to the WiFi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp8266-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n",
client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// publish and subscribe
client.publish(topic, "hello emqx");
client.subscribe(topic);
}
void loop() {
client.loop();
}
Introduction
• An explanation of the technologies used: ESP8266, EMQX broker, and MQTT protocol.
Execution Summary
• A detailed account of how the students set up and configured the ESP8266 and connected it to
the EMQX broker.
• Describe the process of using MQTTExplorer or MQTTx to send and receive messages.
Results
• Detailed results of the implementation, including screenshots of the system in operation (e.g.,
MQTT messages being published and subscribed, actions performed by the ESP8266 like LED
control and servo movement).
• Any observations on the system’s performance, including responsiveness and any potential
issues encountered.
Discussion
• Analysis of how the system worked. Discuss the role of MQTT in IoT communications based on
the lab experience.
• Discuss any discrepancies between expected and actual results and possible reasons for these
discrepancies.
Conclusion
• Reflection on the benefits and limitations of using MQTT for IoT device control.
2. Video Demonstration
• The operational demonstration of controlling the LED and servo motor via MQTT messages.
• A document that includes a review of the provided code. Students should explain each part of
the code, how it contributes to the functionality of the project, and any changes they made.
• Highlight any parts of the code that were particularly challenging or required debugging.
4. Reflection Essay
• How the experience might influence future projects or career choices in the field of IoT.
Submission Guidelines
• All documents should be submitted in PDF format, except the video, which should be uploaded
to a suitable platform and linked within the lab report.
• Ensure all files are clearly named and organized, with the student name(s) and ID(s) included in
each file.