MQTT Implementation: ESP32 with PubSubClient Library
Implement MQTT communication on ESP32 using the PubSubClient library to publish data to a broker like Mosquitto or AWS IoT.
Description
This tutorial explains how to implement MQTT protocol on the ESP32 development board using the PubSubClient library. You'll learn how to connect the ESP32 to a Wi-Fi network, set up a local MQTT broker (Mosquitto), configure the ESP32 as an MQTT client, and publish sensor data to the broker. The guide also covers optional AWS IoT Core integration for cloud-based communication.
Required Components
- ESP32 Development Board
- Wi-Fi Network
- MQTT Broker (Mosquitto, AWS IoT Core, or similar)
- Optional: Sensors (e.g., DHT11)
Steps
- Set Up MQTT Broker (Mosquitto)
Install Mosquitto using `sudo apt install mosquitto mosquitto-clients` and start the service with `sudo systemctl start mosquitto`. Ensure it's running on port 1883.
- Install PubSubClient Library
Open Arduino IDE → Sketch → Include Library → Manage Libraries → Search and install 'PubSubClient' library.
- Configure the MQTT Client on ESP32
Include WiFi and PubSubClient libraries. Define the MQTT broker IP, port, and credentials. Add your Wi-Fi SSID and password.
- Set Up Wi-Fi and MQTT Client
Create a `setup_wifi()` function to connect to Wi-Fi. Initialize PubSubClient with server and callback in `setup()`.
- Publish Data to MQTT Broker
Create a `loop()` function to check MQTT connection, call `reconnect()` if needed, and publish sensor data every 10 seconds.
- MQTT Callback
Define a `mqtt_callback()` function to handle incoming MQTT messages and print them to Serial Monitor.
- Monitor Data from MQTT Broker
Use MQTT Explorer or MQTT.fx to subscribe to `esp32/sensorData` topic and monitor the published data in real-time.
- Use AWS IoT Core (Optional)
Create an AWS IoT Thing, download certificates, and update the MQTT configuration in the code to connect to AWS IoT Core securely using TLS.
Code: mqtt_esp32_pubsubclient.ino
1#include <WiFi.h>
2#include <PubSubClient.h>
3
4const char* ssid = "your_wifi_ssid";
5const char* password = "your_wifi_password";
6const char* mqtt_server = "mqtt.eclipse.org";
7const char* mqtt_username = "your_username";
8const char* mqtt_password = "your_password";
9const int mqtt_port = 1883;
10
11WiFiClient espClient;
12PubSubClient client(espClient);
13
14void setup_wifi() {
15 delay(10);
16 Serial.println();
17 Serial.print("Connecting to WiFi...");
18
19 WiFi.begin(ssid, password);
20 while (WiFi.status() != WL_CONNECTED) {
21 delay(1000);
22 Serial.print(".");
23 }
24
25 Serial.println("Connected to WiFi");
26}
27
28void mqtt_callback(char* topic, byte* payload, unsigned int length) {
29 Serial.print("Message arrived on topic: ");
30 Serial.println(topic);
31 String message = "";
32 for (int i = 0; i < length; i++) {
33 message += (char)payload[i];
34 }
35 Serial.println("Message: " + message);
36}
37
38void reconnect() {
39 while (!client.connected()) {
40 Serial.print("Attempting MQTT connection...");
41 if (client.connect("ESP32Client", mqtt_username, mqtt_password)) {
42 Serial.println("connected");
43 client.subscribe("esp32/topic");
44 } else {
45 Serial.print("failed, rc=");
46 Serial.print(client.state());
47 Serial.println(" try again in 5 seconds");
48 delay(5000);
49 }
50 }
51}
52
53void setup() {
54 Serial.begin(115200);
55 setup_wifi();
56 client.setServer(mqtt_server, mqtt_port);
57 client.setCallback(mqtt_callback);
58}
59
60void loop() {
61 if (!client.connected()) {
62 reconnect();
63 }
64 client.loop();
65 String sensorData = "Temperature: 25.5°C";
66 client.publish("esp32/sensorData", sensorData.c_str());
67 delay(10000);
68}