MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol that uses a publish/subscribe model for IoT (Internet of Things). This blog introduces MQTT for IoT and uses an MQTT IoT project to display how MQTT works for IoT applications.
In this article:
Part 1. What is MQTT for IoT Part 2. MQTT IoT Project: MQTT-Based Temperature Monitoring System with ESP32 Part 3: IoT applications of MQTT Part 4:One-Stop IoT PCBA Manufacturer PCBONLINE from R&D to Box BuildsWhat is MQTT for IoT
MQTT is designed for constrained devices and low-bandwidth, high-latency, or unreliable networks. Due to its efficiency and simplicity, MQTT has become a key technology in IoT applications, where reliable communication between devices is critical.
Key features of MQTT
- Lightweight protocol: MQTT reduces overhead by using minimal control packets.
- Publish/subscribe model: Instead of direct device-to-device communication, devices publish messages to topics, and subscribers receive messages from those topics.
- Reliable message delivery: MQTT offers three Quality of Service (QoS) levels: QoS 0 - at most once delivery, QoS 1 -at least once delivery, and QoS 2 - exactly once delivery.
- Retained messages: A broker can retain the last message sent to a topic, ensuring new subscribers immediately receive the latest data.
- Testament: Devices can define a "last will" message sent by the broker if they disconnect unexpectedly.
How MQTT works
1. A broker acts as a central hub that facilitates communication between devices.
2. Devices (clients) can either publish data on a specific topic or subscribe to a topic to receive updates.
3. Messages are routed by the broker based on topics, and subscribers receive relevant updates in real-time.
Popular MQTT brokers
- Eclipse Mosquitto: Open-source MQTT broker with lightweight implementation.
- HiveMQ: A commercial MQTT broker known for scalability.
- AWS IoT Core: Managed cloud-based MQTT broker.
Why MQTT matters
Scalability and flexibility: MQTT can easily scale from small home automation setups to large industrial systems. Its topic-based messaging structure allows developers to add new devices or services without restructuring existing systems.
Reliability: By offering multiple Quality of Service (QoS) levels, MQTT ensures that messages are delivered according to the specific requirements of the application, whether low-latency updates or mission-critical data accuracy.
Ease of integration: MQTT's simplicity and compatibility with a wide range of devices and platforms, including ESP32 and cloud services, make it an ideal choice for both hobbyists and enterprises.
Cost-effectiveness: Given its low bandwidth requirements, MQTT reduces operational costs, particularly in remote monitoring applications where data transfer costs can be significant.
The MQTT protocol stands as a cornerstone in the realm of IoT communication, uniquely designed to meet the challenges posed by resource-constrained devices and unreliable networks. Its lightweight nature, combined with the powerful publish/subscribe messaging model, ensures efficient and seamless data transmission between interconnected systems. This makes MQTT the go-to protocol for applications that demand real-time updates and low power consumption.
MQTT IoT Project: MQTT-Based Temperature Monitoring System with ESP32
Below, you can find a guide to an MQTT IoT project — an MQTT-based temperature monitoring system with ESP32.
Objective
Create a temperature monitoring system using an ESP32 microcontroller. The ESP32 will:
- Measure temperature using a sensor.
- Publish the temperature readings to an MQTT broker.
- Allow subscribers (like a mobile app or dashboard) to receive real-time temperature updates.
Materials Needed
- ESP32 microcontroller
- DHT11 or DHT22 temperature and humidity sensor
- Resistors, breadboard, and jumper wires
- A computer with Arduino IDE installed
- MQTT broker (e.g., Eclipse Mosquitto)
Circuit Schematic Description
The schematic illustrates the connections between the ESP32 and the DHT11 sensor. The DHT11's data pin connects to one of the ESP32's GPIO pins 34. A pull-up resistor of 10k ohm ensures reliable data transmission. The ESP32 communicates with the broker via Wi-Fi.
PCB Layout Description
The PCB design compactly organizes components, optimizing space and minimizing interference. The layout includes labeled connectors for the DHT11 sensor, ESP32 module, and power supply.
Code for ESP32 MQTT Temperature Monitoring
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// Wi-Fi credentials
const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";
// MQTT broker details
const char* mqttServer = "broker.hivemq.com"; // Replace with your broker's address
const int mqttPort = 1883;
const char* mqttTopic = "home/temperature";
// DHT sensor setup
#define DHTPIN 34 // GPIO pin connected to DHT sensor
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// Initialize WiFi and MQTT client
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
dht.begin();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Connect to MQTT broker
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP32Client")) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
delay(2000);
}
}
}
void loop() {
float temperature = dht.readTemperature(); // Read temperature
if (isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Publish temperature to MQTT topic
char tempString[8];
dtostrf(temperature, 1, 2, tempString);
client.publish(mqttTopic, tempString);
Serial.print("Temperature published: ");
Serial.println(tempString);
delay(5000); // Publish every 5 seconds
}
Testing and Deployment
1. Set up the MQTT broker (e.g., Eclipse Mosquitto) on a server or cloud.
2. Run the ESP32 code. Ensure it connects to Wi-Fi and the MQTT broker.
3. Subscribe to the home/temperature topic using an MQTT client like MQTT Explorer or a mobile app.
This project demonstrates MQTT's simplicity and efficiency in transmitting real-time data, making it ideal for IoT applications.
The practical example of the temperature monitoring system with ESP32 highlights how MQTT empowers developers to create robust IoT solutions with minimal complexity. By understanding MQTT's core features and exploring its applications, developers can unlock immense potential in various domains, contributing to the rapid advancement of IoT technology.
IoT applications of MQTT
From smart homes and industrial IoT to healthcare and smart grids, MQTT is redefining how devices communicate, enabling innovations that improve convenience, efficiency, and safety. It plays a pivotal role in creating a connected world where data flows seamlessly to deliver actionable insights.
- Smart home automation: MQTT enables seamless communication between smart devices like lights, thermostats, and security systems. For instance, a motion sensor can publish alerts to a topic, which smart lights subscribe to, triggering illumination.
- Industrial IoT (IIoT): Factories use MQTT to monitor machinery and sensors. Real-time updates allow predictive maintenance, reducing downtime and optimizing performance.
- Vehicle telematics: MQTT facilitates vehicle data sharing for fleet management, GPS tracking, and real-time diagnostics.
- Healthcare: IoT devices in healthcare use MQTT to transmit vital data like heart rate and oxygen levels from wearable devices to cloud servers.
- Energy monitoring: MQTT helps monitor power usage in smart grids, enhancing energy efficiency and sustainability.
One-Stop IoT PCBA Manufacturer PCBONLINE from R&D to Box Builds
No matter what protocols your project uses, MQTT, LoRa, NB-IoT, etc, you can work with the one-stop PCBA (printed circuit board assembly) manufacturer PCBONLINE with R&D capabilities for turnkey electronics manufacturing services under one roof.
Founded in 1999, PCBONLINE has two large advanced PCB manufacturing bases, one PCB assembly factory, stable supply chains, and an R&D team.
PCBONLINE is a source factory IoT PCBA manufacturer and provides hardware and software R&D, prototyping/sampling, PCB fabrication, component sourcing, PCB assembly, PCBA value-added, and box-build assembly.
PCBONLINE offers one-on-one engineering support and free design for manufacturing (DFM) to ensure smooth manufacturing and successful results for your IoT PCBA project.
PCBONLINE has long-term cooperation with mainstream MCU companies such as Espressif and the supply of MCUs and components for IoT PCBA is fast and steady.
High-quality IoT PCBA manufacturing certified with ISO 9001:2015, ISO 14001:2015, IATF 16949, RoHS, REACH, UL, and IPC-A-610 Class 2/3.
When your IoT PCBA project enters the bulky production stage, PCBONLINE refunds the fees of R&D, sampling, and PCBA functional testing.
No matter what quantity of IoT PCB boards you want, you can enjoy free and considerate engineering support throughout your project. To get a quote for your MQTT IoT PCBA project, contact info@pcbonline.com.
Conclusion
This blog gives a brief introduction to the MTT protocol and how it is used in IoT applications through an MQTT IoT project. In a world increasingly reliant on interconnected systems, MQTT is more than a protocol; it is a bridge that transforms isolated devices into intelligent, collaborative networks driving the future of technology. If you have questions about your MQTT IoT device project, chat with PCBONLINE from the online chat window.
PCB assembly at PCBONLINE.pdf