Try Embedded

MQTT sensor node (ESP32-C3)

Publish a reading to an MQTT broker every 2 s, switch an LED from a command topic, and announce the node with a retained status and a last will.

Communication · Intermediate

In a real product: Smart home sensor (Smart home): Publishes readings to the home hub over MQTT and takes commands back.

MQTT is how most connected devices talk to the cloud: each one keeps a connection to a broker, publishes readings to topics, and subscribes to the topics its commands come on. Here an ESP32-C3 publishes the potentiometer's value every 2 seconds and switches its LED when the cloud publishes on or off to cmd/led. The simulated broker broker.lab sends those commands at 5 s and 9 s.

What you'll learn

  • Connecting to a broker with a client id, a username and a password
  • Publishing, and subscribing with a wildcard (cmd/#)
  • Why mqtt.loop() has to run often, and why the reading is timed with millis() instead of delay()
  • Retained messages and the last will: how a dashboard knows a node is offline

How it works

PubSubClient sends MQTT over a WiFiClient (TCP, port 1883). connect gives the broker a last will: a message it publishes for the node, retained, if the connection drops without a proper DISCONNECT. Once connected the node publishes online to the same topic, retained, so anyone who subscribes later sees the current state at once.

Messages that arrive are only read inside mqtt.loop(), which also sends the keep-alive pings; a sketch that sits in delay() misses its commands. The callback onMessage gets the topic and the payload as bytes, not a string.

The broker, its username and password, and the commands it sends are set in the network section of diagram.json. Open the Network panel under the canvas to see the connect, the subscription, every publish and the broker's commands.

Try this

  • Turn the potentiometer and watch the published values in the Network panel.
  • Change the password in the sketch: connect fails with state 4 (bad credentials) and the node retries.
  • Add a { "atMs": 7000, "topic": "cmd/interval", "payload": "500" } publish and make the node publish that often.

sketch.ino

// An MQTT sensor node: publishes the potentiometer on GPIO 0 every 2 s, switches the LED on GPIO 4 from the
// cmd/led topic, and keeps a retained status with a last will, so the broker says "offline" if the node vanishes.
#include <WiFi.h>
#include <PubSubClient.h>

const char *BROKER = "broker.lab";
const char *STATUS_TOPIC = "devices/node-1/status";
const int POT = 0;
const int LED = 4;

WiFiClient net;
PubSubClient mqtt(net);

void onMessage(char *topic, byte *payload, unsigned int length) {
  String text;
  for (unsigned int i = 0; i < length; i++) text += (char)payload[i];
  Serial.printf("<- %s: %s\n", topic, text.c_str());
  if (String(topic) == "cmd/led") digitalWrite(LED, text == "on" ? HIGH : LOW);
}

void connectMqtt() {
  while (!mqtt.connected()) {
    Serial.print("MQTT connecting... ");
    // The will: published for us, retained, if the connection drops without a DISCONNECT.
    if (mqtt.connect("node-1", "node", "lab-pass", STATUS_TOPIC, 1, true, "offline")) {
      Serial.println("connected");
      mqtt.publish(STATUS_TOPIC, "online", true);
      mqtt.subscribe("cmd/#");
    } else {
      Serial.printf("failed (state %d), retrying in 2 s\n", mqtt.state());
      delay(2000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  WiFi.begin("TryEmbedded", "");
  while (WiFi.status() != WL_CONNECTED) delay(100);
  Serial.printf("Wi-Fi: %s\n", WiFi.localIP().toString().c_str());
  mqtt.setServer(BROKER, 1883);
  mqtt.setCallback(onMessage);
}

void loop() {
  connectMqtt();
  mqtt.loop();   // reads incoming messages and keeps the connection alive: call it often

  static unsigned long last = 0;
  if (millis() - last >= 2000) {
    last = millis();
    char value[8];
    snprintf(value, sizeof value, "%d", analogRead(POT));
    mqtt.publish("sensors/node-1/pot", value);
    Serial.printf("-> sensors/node-1/pot: %s\n", value);
  }
}

Lessons behind it