A Complete Guide on MQTT ESP8266 Wi-Fi
Wireless Connectivity
Ashna N November 25, 2024

The Internet of Things (IoT) redefines how we interact with technology. It is obvious that IoT bridges the gap between our physical and digital realm. Today, from smart home systems to adjusting lighting and temperature automatically to industrial sensors that monitor machinery in real time, IoT devices rule the roost. At the core of the Internet of Thing’s functionality is the smooth data exchange between devices. For this, one of the most commonly used protocols for device communication is MQTT (Message Queuing Telemetry Transport) or MQ Telemetry Transport.

In this blog, we shall explain MQTT in detail, its key applications, and the ways to configure an MQTT broker with Mosquitto. It further explores its capabilities with the ESP8266 Wi-Fi module.

What is MQTT?

What is MQTT

MQTT, or Message Queuing Telemetry Transport, features a lightweight architecture created for low-bandwidth, high-latency, or unstable networks. Since it is lightweight, it is one of the most reliable ways to help devices send and receive messages. Its lightweight characteristic makes it a great protocol choice for IoT applications. It features a client-broker-server model, and the broker acts as the central hub. It manages message distribution between clients. In this MQTT system, there are essentially three significant roles: 

Publisher: An application or a device that transmits information/messages to the broker on specific topics. Also, it provides information or commands to other devices. 

Subscriber: A device or application that listens for messages on specific topics from the broker. It receives updates and commands from publishers. 

Broker: The core component of the MQTT architecture. The broker receives and distributes messages from publishers to the appropriate subscribers. The distribution is done based on the topics they are interested in. 

This architecture focuses on reliable communication among devices. Therefore, it makes MQTT suitable for Internet of Things (IoT) applications. 

What are the most common industrial applications of MQTT? 

Monitoring industrial assets 

Manufacturing businesses make use of MQ Telemetry Transport to monitor equipment performance and maintenance needs. 

Healthcare 

MQTT medical devices help protect patient information and send them to healthcare service providers. 

Agriculture  

Using MQTT, farmers receive reports on soil conditions with the sensors in the field. Further, it helps them to streamline crop growth. 

Transportation 

MQTT is ideal for vehicle fleet services, that it is easy to report location and status in real-time. 

Energy Management 

Smart grids in the energy industrial sector make use of MQ Telemetry Transport for efficient and better power distribution. 

Smart Homes 

MQTT enables automation and control of devices such as lights, thermostats, and security systems. 

ESP8266

ESP8266

The ESP8266 revolutionizes the world of the Internet of Things (IoT). This mighty chip (even though it is tiny) is fundamentally a replica of a minicomputer with built-in Wi-Fi features. Espressif Systems has created ESP8266. This module helps developers to connect devices to the internet wirelessly.  

Further, it can communicate with various sensors and actuators. The ESP8266 serves as an ideal platform for building intelligent home automation systems, and other IoT applications. It is compatible with the Arduino IDE. Therefore, it is easy for both beginners and experienced developers to code and deploy projects successfully.  

Key Features

Wi-Fi Connectivity

802.11 b/g/n support 

The ESP8266 backs standard Wi-Fi protocols. Further, it makes ESP8266 work with home and industrial network. 

Integrated TCP/IP stack 

ESP8266 comes with an embedded TCP/IP stack. Therefore, it helps in direct communication with internet services. 

Station/Soft Access Point mode 

The module functions as a client (station) that connects to a router. Also, it works as an access point (AP) that other devices can connect to. 

Microcontroller Core

Tensilica Xtensa LX106 32-bit processor 

The ESP8266 has a powerful core running at 80 MHz or 160 MHz. It makes ESP8266 ideal for processing lightweight tasks. 

RAM 

 50 kB of available RAM, with 96 kB for data and instruction caching. 

Flash Memory 

The module features 512 kB to 4 MB of flash memory. It further enables the storage of larger programs and facilitates effortless firmware updates. 

GPIO Pins

General-purpose Input/Output pins (GPIO) 

The ESP8266 possesses up to 17 GPIO pins. These pins help to interface with sensors, relays, LEDs, and other peripherals. 

The GPIO pins support PWM (Pulse Width Modulation), I2C, SPI, and UART protocols. It makes the module suitable for many hardware interfaces. 

Power Efficiency

Low power consumption 

The ESP8266 is optimized for low-power operation. It has several sleep modes (deep sleep, light sleep). Further, it provides energy utility when there is no active data transmission. 

The ESP8266 operates at a voltage of 3.3V. It is needed when connecting to external components like sensors. An external power supply/voltage regulator might be needed when using 5V systems. 

Integrated Peripherals

ADC (Analog to Digital Converter) 

The ESP8266 includes a single 10-bit ADC. Therefore it allows the ESP8266 to read analog inputs from sensors, for example, temperature or light sensors. 

UART 

Serial communication is backed through the UART interface. It is useful for debugging and communicating data with other devices. 

SPI and I2C 

These serial communication protocols make it easy to interface with external hardware like displays, sensors, and storage devices. 

Network Security

WEP, WPA, and WPA2 Encryption 

The module supports modern Wi-Fi encryption protocols. Additionally, it ensures the secure transmission of data. 

TLS/SSL 

Using libraries such as OpenSSL, the ESP8266 handles safe transfer of data over MQTT (FTPS, HTTPS). It is essential for IoT applications as data privacy is a priority. 

ESP8266 Modules 

The ESP8266 comes in several module formats. The most common are: 

ESP-01 

One of the most fundamental versions of ESP8266 with 2 GPIO pins and a small flash size. It is ideal for simple Wi-Fi applications. 

ESP-12E/F 

A more advanced version with 17 GPIO pins, larger flash memory, and a built-in antenna.  

NodeMCU 

A development board based on the ESP-12E/F module. It has a USB interface with built-in firmware and supports Arduino IDE or Lua scripting. 

What are the advantages of Using MQTT with ESP8266? 

Efficiency 

MQTT’s low bandwidth requirements help the ESP8266 to ensure reduced power consumption. 

Reliability 

The ESP8266 maintains stable connections over MQTT that it offers smooth performance even in environments with unreliable and fluctuating network coverage. 

Scalability 

Using MQ Telemetry Transport, the ESP8266 can communicate with multiple devices. Therefore, it becomes ideal for building scalable IoT networks. 

Real-Time Communication 

MQTT backs real-time data transfer. As a result, it allows the ESP8266 to send and receive messages immediately. 

Low Latency 

The lightweight nature of MQTT helps the ESP8266 to communicate with the least delay. Therefore, it is most suitable for time-sensitive applications such as emergency notification systems and smart manufacturing solutions.

Security Features 

When combined with TLS/SSL, MQ Telemetry Transport ensures secure communication channel. It protects the exchange of sensitive information between the ESP8266 and the broker free from cyber threats. 

How do you set up the Mosquitto MQTT Broker? 

 Prerequisites  

  • Linux system
  • Internet connection
  • System management access

 Steps 

 1. Install Mosquitto MQTT Broker 

  • Refresh Package Lists: Open a terminal and execute to update the package indexes 

                         sudo apt update  

  • Install Mosquitto and Client Utilities: 

            sudo apt install mosquitto mosquitto-clients

  • Enable and Start the Mosquitto Service: 

           sudo systemctl enable mosquito
           sudo systemctl start mosquitto 

  • Start Mosquitto Broker on a Custom Port 
  • Access the configuration file using the command below: 

                                 sudo nano /etc/mosquitto/mosquitto.conf 

  • In the configuration file, add a listener line: 

                                 listener 1884 

            It will set the broker to listen on port 1884. 

  • Restart Mosquitto: 

                                sudo systemctl restart mosquitto 

  • Configure User Authentication
  • Create a password file. Configure user credentials for secure login  
  • Create Password File: 

                      sudo mosquitto_passwd -c /etc/mosquitto/passwd your_username 

Replace your username with the desired username. Enter a password when you are asked to give the password 

  • Edit the Mosquitto Configuration File: Open the configuration file with a text editor: 

                    sudo nano /etc/mosquitto/mosquitto.conf

            Add the following lines for authentication: 

password_file /etc/mosquitto/passwd
allow_anonymous false 

  • Restart Mosquitto Service:  

sudo systemctl restart mosquitto 

  • Enable and Configure Logging

Logging helps you monitor broker activities and fix issues through troubleshooting. 

  • Edit the Configuration File again: Add the following commands to configuration file: 

# Log to a file 

log_dest file /var/log/mosquitto/mosquitto.log 

# Log to the console 

log_dest stdout 

  • Create Log Directory and Set Permissions: 

sudo mkdir -p /var/log/mosquitto
sudo chown mosquitto:mosquitto /var/log/mosquitto 

  • Restart the Service: 

sudo systemctl restart mosquitto 

  • View Log File: 

sudo cat /var/log/mosquitto/mosquitto.log 

  • Test with Publisher and Subscriber
  • Run a Subscriber: In one terminal window, start a subscriber to listen to a topic, such as test/topic: 

mosquitto_sub -h localhost -p 1884 -t “test/topic” -u your_username -P your_password 

  • Publish a Message: In a new terminal window, publish a message to the same topic: 

mosquitto_pub -h localhost -p 1884 -t “test/topic” -m “Welcome” -u your_username -P your_password 

  • Verify: The subscriber should display the message “Welcome”. 

 MQTT with ESP8266 

   Prerequisites 

  • An ESP8266 module (NodeMCU or similar) 
  • Arduino IDE installed on your computer 
  • ESP8266 board support added to the Arduino IDE 
  • PubSubClient library installed 

Steps in Connecting MQTT with ESP8266 

Step 1: Setting Up the Arduino IDE for ESP8266 

 As a first step, prepare the Arduino IDE to work with the ESP8266 module: 

  • Open Arduino Integrated Development Environment and go to File > Preferences. 
  • To save the changes, click ‘OK’ 
  • Open Tools, then go to Board, and then to Boards Manager. 
  • Search for “ESP8266” and install the package. 
  • Now Arduino IDE is all set to program ESP8266 boards. 

Step 2: Installing the PubSubClient Library 

  • Open Sketch, then Include Library and then finally to Manage Libraries. 
  • Search for “PubSubClient” and install it. The library enables your ESP8266 to communicate with the MQTT broker. 

Step 3: Uploading the Code for MQTT Connection 

Upload the basic example code for connecting our ESP8266 to a Wi-Fi network and an MQTT broker from PubSubClient GitHub Repository (http://bit.ly/4f8oKA4). The code helps subscribe to topics and receive messages. 

Step 4: Configuration 

Before uploading the code, make sure to replace the placeholders with your specific details: 

  • ssid: Your Wi-Fi network name 
  • password: Your Wi-Fi password 
  • mqtt_server: The address of your MQTT broker 

Step 5: Upload and Test 

  • Select your board and port in the Arduino IDE. 
  • Upload the sketch to your ESP8266. 
  • Open the Serial Monitor to track the connection process. You would see messages indicating a successful connection to Wi-Fi and the MQTT broker.

What is the practical application of ESP8266 and MQTT?

Practical Application of ESP8266 and MQTT

We can create a simple system to control an LED light remotely using ESP8266 and MQTT to empower the Internet of Things (IoT).  

In this setup, we use two ESP8266 devices: one device as a publisher to transmit commands to control the LED while the other as a subscriber to receive the commands and control the LED accordingly.  

You can connect the publisher ESP8266 to a physical switch or a mobile app, allowing users to send messages to ‘switch on light’ or ‘switch off light’ to a specific topic, for example, “home/led/control.” The subscriber ESP8266 listens for these messages on the same topic. As soon as it receives a command from the user, it turns the LED on or off in accordance with the instruction. 

In this system, the broker acts as the central hub. It handles smooth communication between the publisher and subscriber. Both ESP8266 devices connect to the broker, which offers flexible hosting- locally or on the cloud. It helps exchange messages without fail. After changing the LED’s state, the subscriber can publish a status update to another topic, such as “home/led/status.” It updates the user about the LED’s current state, that is if it is on or off. The two-way communication helps users control the LED from anywhere, anytime. Further, it translates to user convenience and what’s more enhances home automation. 

Final Remarks 

Using MQTT with the ESP8266 sets the stage for creating smart, connected devices for the Internet of Things (IoT) ecosystem. Since it is lightweight in nature, it can efficiently handle communication over low-bandwidth networks. As a result, it is ideal for applications used for smart homes and industrial automation. We have discussed the fundamentals of MQ Telemetry Transport its key applications, and the configuration process for an MQTT broker using Mosquitto. Using MQTT’s reliable protocol establishes a strong foundation for further advancements, including tasks like sensor monitoring, remote device control, and developing more complex IoT systems.

At ThinkPalm our IoT specialists harness the endless potential of MQTT and ESP8266 to discover innovative solutions. With our wide expertise in IoT development, ThinkPalm helps businesses make the most of MQTT capabilities. It helps create scalable, fail-proof IoT solutions to empower businesses with the connected world. 

Ready to embrace MQTT-enabled IoT solutions? Explore ThinkPalm’s expertise Reach out to our IoT experts

 


Author Bio

Ashna N is an enthusiastic embedded engineer in the Wireless and Connectivity business unit, specializing in IoT solutions. With a solid foundation in electronics engineering, she is highly driven to discover and develop pioneering technologies that bridge the gap between devices and the digital world.