How to Publish Data From an Arduino Microcontroller Via MQTT?

by kavishchoudhary1935 in Circuits > Arduino

39 Views, 1 Favorites, 0 Comments

How to Publish Data From an Arduino Microcontroller Via MQTT?

MQTT_1.png

This guide will walk you through the process of setting up MQTT on an Arduino (using an Arduino Nano 33 IoT in this example) and testing it with a local MQTT client tool like MQTTX. MQTT is a lightweight messaging protocol perfect for IoT applications, making it a popular choice for communication between devices.


Supplies

What You'll Need

  1. Arduino Nano 33 IoT (or similar with WiFi support)
  2. WiFi network credentials
  3. MQTT broker (we'll use a public broker, but you can also set up a local broker)
  4. MQTTX - a desktop MQTT client for testing (available for Windows, MacOS, and Linux)

Install Required Libraries

Screenshot 2024-11-11 100235.png

For this setup, we'll use two libraries: WiFiNINA for WiFi connectivity and PubSubClient for MQTT communication.

  1. Open the Arduino IDE.
  2. Go to Sketch > Include Library > Manage Libraries.
  3. Search for and install WiFiNINA and PubSubClient.

Connect to WiFi and MQTT Broker

First, configure the Arduino to connect to WiFi and the MQTT broker.

Here's a basic sketch:

#include <WiFiNINA.h>
#include <PubSubClient.h>

// WiFi credentials
const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

// MQTT Broker (replace with your broker if using a local one)
const char* mqtt_server = "broker.hivemq.com"; // Public broker for testing
const int mqtt_port = 1883;
const char* mqtt_topic = "test/arduino";

WiFiClient wifiClient;
PubSubClient client(wifiClient);

// Connect to WiFi
void setupWiFi() {
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi.");
}

// Reconnect to MQTT if disconnected
void reconnectMQTT() {
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("ArduinoClient")) {
Serial.println("connected");
client.subscribe(mqtt_topic); // Subscribe to topic
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
delay(2000);
}
}
}

void setup() {
Serial.begin(9600);
setupWiFi();

client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}

// Define a callback function to handle incoming messages
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}

void loop() {
if (!client.connected()) {
reconnectMQTT();
}
client.loop();

// Publish a test message every 5 seconds
static unsigned long lastMsgTime = 0;
unsigned long now = millis();
if (now - lastMsgTime > 5000) {
lastMsgTime = now;
String message = "Hello from Arduino!";
Serial.print("Publishing message: ");
Serial.println(message);
client.publish(mqtt_topic, message.c_str());
}
}

Explanation of the Code

  1. setupWiFi(): Connects to WiFi using the provided SSID and password.
  2. reconnectMQTT(): Reconnects to the MQTT broker if the connection is lost.
  3. callback(): Handles incoming MQTT messages, printing the message content.
  4. loop(): Publishes a "Hello from Arduino!" message every 5 seconds to the MQTT topic.

Upload this code to your Arduino.

Download and Set Up MQTTX

MQTTX is a powerful MQTT client that can be used to test MQTT connections.

  1. Download MQTTX from MQTTX GitHub releases.
  2. Install MQTTX on your computer.


Test the MQTT Connection Using MQTTX

Now, you’ll use MQTTX to connect to the same broker and topic as your Arduino.

  1. Open MQTTX.
  2. Create a New Connection:
  3. Click on New Connection.
  4. Set the Client ID (e.g., "MQTTXClient").
  5. Set the Host to broker.hivemq.com (or use your local broker’s IP if applicable).
  6. Set the Port to 1883.
  7. Click Connect.
  8. Subscribe to the Topic:
  9. Once connected, click on Subscribe and enter the topic name: test/arduino.
  10. Click Confirm to start subscribing to messages on this topic.
  11. View Published Messages:
  12. MQTTX should now show any messages published to test/arduino.
  13. If everything is set up correctly, you should see "Hello from Arduino!" messages every 5 seconds.
  14. Test Sending Messages to Arduino:
  15. Go to the Publish tab in MQTTX.
  16. Set the Topic to test/arduino and type a test message in the payload (e.g., "Message from MQTTX").
  17. Click Publish.
  18. Your Arduino should print this message in the Serial Monitor, confirming it received the MQTT message.

Troubleshooting

If you encounter issues:

  1. Check WiFi Connection: Verify your SSID and password are correct.
  2. Verify Broker Connection: Ensure the broker (like HiveMQ or your local one) is reachable.
  3. Check MQTT Settings: Ensure MQTT server, port, and topic match between Arduino and MQTTX.
  4. Monitor Serial Output: Use the Serial Monitor to view debug messages from your Arduino.


Customizing for a Local Broker

To use a local broker instead of a public one, you can install Mosquitto, a popular MQTT broker.

  1. Install Mosquitto on your computer. For installation instructions, refer to the Mosquitto website.
  2. Start Mosquitto:
  3. Run Mosquitto by opening a terminal and typing mosquitto -v (on Linux/macOS) or starting the Mosquitto service on Windows.
  4. Mosquitto will run on localhost (IP: 127.0.0.1) and port 1883 by default.
  5. Update Arduino Code:
  6. Change the mqtt_server variable in the Arduino code to mqtt_server = "your_local_ip_address".
  7. Connect MQTTX:
  8. In MQTTX, change the Host field to localhost or your computer’s IP address.
  9. Connect and test as described earlier.