Section outline

  • MQTT Basics – Lightweight Messaging for IoT

    MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol widely used in IoT systems. It allows devices like sensors, robots, and microcontrollers to communicate over the internet with low bandwidth and power usage.

    • 🌐 What is MQTT?

      MQTT is a publish-subscribe protocol. Instead of sending data directly between devices, all communication happens through a central broker (like a post office).

      🧩 How MQTT Works

      • Broker: The central server that handles messages
      • Publisher: A device (e.g. ESP32) that sends data
      • Subscriber: A device or app that receives data
      • Topic: A channel or label used to organize messages (like /weather/temp)

      Example: Your ESP32 publishes temperature data to the topic /robot/weather/temp. A mobile app subscribes to that topic and displays the latest temperature reading.

      📦 Why Use MQTT?

      • Low bandwidth – ideal for IoT devices
      • Reliable – even over spotty Wi-Fi
      • Flexible – one message can be received by many devices
    • 🔧 MQTT Terminology at a Glance

       

      Term Meaning
      Broker Server that manages all messages
      Client Any device connected to broker (ESP32, mobile app, etc.)
      Publish Send message to broker under a topic
      Subscribe Listen for messages on a specific topic
      Topic Label for organizing messages (e.g. /robot/temp)

       

    • 💻 Sample Code (ESP32 Publishing Data)

      #include <WiFi.h>
      #include <PubSubClient.h>
      
      const char* ssid = "your_SSID";
      const char* password = "your_PASSWORD";
      const char* mqtt_server = "broker.hivemq.com";
      
      WiFiClient espClient;
      PubSubClient client(espClient);
      
      void setup() {
        Serial.begin(115200);
        WiFi.begin(ssid, password);
        while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          Serial.print(".");
        }
        client.setServer(mqtt_server, 1883);
      }
      
      void loop() {
        if (!client.connected()) {
          reconnect();
        }
        client.loop();
      
        // Publish data
        client.publish("/robot/weather/temp", "28.5");
        delay(5000); // send every 5 seconds
      }
      
      void reconnect() {
        while (!client.connected()) {
          if (client.connect("ESP32Client")) {
            client.subscribe("/robot/commands");
          } else {
            delay(2000);
          }
        }
      }
      

      ⚠️ Note

      • Use public MQTT brokers like broker.hivemq.com for testing
      • Always keep topic names clear and structured (e.g., /robot/status)
      • For production use, secure brokers and authentication are recommended