MQTT guides · On this page

Send Sensor Readings and Switch an LED over MQTT with an ESP32

Send an ESP32's temperature and humidity readings to an MQTT broker every five seconds, and switch its LED on or off from your phone.

MQTT is how many connected devices talk. The ESP32 connects to a server called a broker and sends each reading to a named topic; your phone, or this page, connects to the same broker and gets them. You don't write an app: any MQTT app works. The sensor is a DHT22; the DHT11 vs DHT22 guide covers it.

Try it first, no parts needed

This is the whole project, running in your browser. Press Run simulation: the ESP32 joins Cirkit's simulated Wi-Fi and connects to a real MQTT broker on the internet, and this page joins the same broker as a second client. Move the temperature slider and watch the new value arrive; press On or Off and watch the LED.

In the simulation

Ready
Open in Cirkit Designer

The air around the DHT22

The sketch reads it every 5 seconds and sends it to the broker.

25.0 °C
60.0 %

ESP32 serial monitor115200 baud

Output appears here when the simulation runs.

On the internet

ESP32 the board in the circuit

Online through Cirkit's servers, port 1883

Stopped

MQTT broker a real server, run by Cirkit

mqtt.cirkitdesigner.com

Passed on
0
Round trip
—

This page a second MQTT client, port 443

Joins when the simulation runs

Not connected
Temperature
—
Humidity
—
LED
—
Send to the LED

Any device on the broker can do the same: a phone app, a laptop, another ESP32.

Try it: set the temperature slider to 30 °C. The ESP32 sends every five seconds of simulated time; at its next send, 30.0 °C travels from the simulated ESP32 through the broker to this page.

Watch it from your own phone: run the circuit to get this run's channel.

Show the messages
  1. None yet.

What the code does

The sketch joins Wi-Fi, makes a random channel name, connects to the broker, then sends a reading every five seconds and listens for "on" and "off".

esp32_mqtt.ino
// ESP32 MQTT: send a DHT22's readings to a broker every 5 s,
// and switch an LED when an "on" or "off" message arrives.
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>

// Your Wi-Fi. CirkitWifi is Cirkit's simulated network.
const char* WIFI_NAME = "CirkitWifi";
const char* WIFI_PASSWORD = "";
// Cirkit's public broker: anyone can read cirkit-learn/.
const char* BROKER = "mqtt.cirkitdesigner.com";
const int BROKER_PORT = 1883;

const int DHT_PIN = 4;
const int LED_PIN = 19;
// The DHT22 needs at least 2 s between readings.
const unsigned long SEND_EVERY_MS = 5000;

DHT dht(DHT_PIN, DHT22);
WiFiClient network;
PubSubClient mqtt(network);

String deviceId;  // random, so no other board uses it
String channel;   // cirkit-learn/<deviceId>
unsigned long lastSent = 0;

// A topic under this board's channel, like ".../led".
String topic(const char* name) {
  return channel + "/" + name;
}

const char* ledState() {
  if (digitalRead(LED_PIN) == HIGH) {
    return "on";
  }
  return "off";
}

void onMessage(char* name, byte* payload,
               unsigned int length) {
  String message;
  for (unsigned int i = 0; i < length; i++) {
    message += (char)payload[i];
  }
  if (message == "on") {
    digitalWrite(LED_PIN, HIGH);
  } else if (message == "off") {
    digitalWrite(LED_PIN, LOW);
  } else {
    return;
  }
  Serial.println("LED " + message);
  mqtt.publish(topic("led/state").c_str(), ledState());
}

void connectToWifi() {
  Serial.print("Connecting to ");
  Serial.println(WIFI_NAME);
  WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
  }
  Serial.print("Wi-Fi connected, IP address ");
  Serial.println(WiFi.localIP());
}

void connectToBroker() {
  while (!mqtt.connected()) {
    Serial.print("Connecting to ");
    Serial.println(BROKER);
    String clientId = "cirkit-" + deviceId;
    if (mqtt.connect(clientId.c_str())) {
      Serial.println("Connected to the broker");
      mqtt.subscribe(topic("led").c_str());
      mqtt.publish(topic("led/state").c_str(), ledState());
    } else {
      Serial.print("Broker connection failed, state ");
      Serial.print(mqtt.state());
      Serial.println("; trying again in 5 s");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);
  dht.begin();
  connectToWifi();

  // Random once Wi-Fi is on: the numbers come from the radio.
  char id[17];
  snprintf(id, sizeof(id), "%08lx%08lx",
           (unsigned long)esp_random(),
           (unsigned long)esp_random());
  deviceId = id;
  channel = "cirkit-learn/" + deviceId;
  Serial.println("Channel: " + channel);

  mqtt.setServer(BROKER, BROKER_PORT);
  mqtt.setCallback(onMessage);
}

void loop() {
  connectToBroker();
  mqtt.loop();  // sends keep-alives, delivers messages

  if (millis() - lastSent >= SEND_EVERY_MS) {
    lastSent = millis();
    float temperature = dht.readTemperature();
    float humidity = dht.readHumidity();
    if (isnan(temperature) || isnan(humidity)) {
      Serial.println("No reading from the DHT22");
      return;
    }
    String t = String(temperature, 1);
    String h = String(humidity, 1);
    mqtt.publish(topic("temperature").c_str(), t.c_str());
    mqtt.publish(topic("humidity").c_str(), h.c_str());
    Serial.println("Sent " + t + " C, " + h + " %");
  }
}
  1. const char* BROKER = "mqtt.cirkitdesigner.com";

    The broker and its port, 1883, MQTT's registered port for connections without encryption. Cirkit's broker is public: anyone can read and publish under cirkit-learn/, so it suits readings, not anything private.

  2. snprintf(id, sizeof(id), "%08lx%08lx",
             (unsigned long)esp_random(),
             (unsigned long)esp_random());

    A random 16-character ID. The sketch makes it after joining Wi-Fi: with the radio on, the ESP32's hardware random number generator gives truly random numbers. The board's channel is cirkit-learn/ plus the ID; every topic it uses starts with it, so it doesn't collide with other boards on the broker.

  3. if (mqtt.connect(clientId.c_str())) {
      Serial.println("Connected to the broker");
      mqtt.subscribe(topic("led").c_str());
      mqtt.publish(topic("led/state").c_str(), ledState());
    } else {

    Connects with a client ID made from the same digits; a broker drops an older connection when a new one uses the same ID. Then it subscribes to …/led, where commands arrive. If the broker can't be reached, it prints why and tries again after five seconds.

  4. mqtt.loop();  // sends keep-alives, delivers messages

    PubSubClient sends keep-alive pings and hands arriving messages to onMessage only from here, so loop() must reach it often while connected. That's why the readings are timed with millis() rather than delay().

  5. mqtt.publish(topic("temperature").c_str(), t.c_str());

    Every five seconds, one message to …/temperature and one to …/humidity, each the reading as text with one decimal. The DHT22 needs at least two seconds between readings.

  6. void onMessage(char* name, byte* payload,
                   unsigned int length) {

    Runs for each message on …/led: "on" or "off" switches GPIO 19, then the board answers on …/led/state, so whoever sent it knows it arrived.

How MQTT works

Here's what happens to one reading. No device sends to another directly; the broker passes each message on.

How a message gets from the ESP32 to the page

ESP32

publishes

<channel>/temperature 24.1

Broker

passes it to every client subscribed to a matching topic

This page

subscribed to <channel>/temperature: gets it

Your phone

subscribed to <channel>/#: gets it

Another board

subscribed to <channel>/led: doesn't get it

A topic name, level by level (the channel is the first two)

cirkit-learnthe area this broker allows7f3a9c21e04b5d88this board's random IDtemperaturewhat the message is

Topic names are levels separated by /. A subscription can use two wildcards: + matches one level, and #, only at the end, matches any number. Subscribing to <channel>/#gets everything this board sends.

IdeaWhat it means here
QoS 0"At most once": each reading is sent once, with no reply and no retry. A lost reading is replaced by the next. PubSubClient only publishes at QoS 0.
Keep-aliveThe longest gap between a client's packets. If the broker hears nothing for 1.5 times that, it drops the client. PubSubClient's default is 15 seconds.
Retained messageA message the broker keeps and gives to anyone who subscribes later. This sketch doesn't use them, and Cirkit's broker refuses them.
WebSocketA web page can't open a plain MQTT connection, so this page sends MQTT inside a WebSocket instead, to wss://mqtt.cirkitdesigner.com/mqtt.

Build it

Now with real parts. Wire it, get the code and set your Wi-Fi, then upload it and follow it from your phone.

You'll need

  • An ESP32 DevKitC (ESP32-WROOM-32) and a USB cable that carries data
  • A DHT22 (AM2302) module with three pins
  • A red LED and a 220 Ω resistor
  • A breadboard and five jumper wires
  • A 2.4 GHz Wi-Fi network with internet access, and a phone or computer with a web browser
  • Software to upload the sketch: Cirkit Designer, free in your browser, or the Arduino IDE
  1. Wire it

    Power the DHT22 from 3V3: its DAT pin goes straight to GPIO 4, and the ESP32's pins aren't rated for 5 V. The LED goes on GPIO 19 through its resistor.

    Tap a connection to see it on the circuit.

    PinConnect to the ESP32Show
    DHT22 VCC (+)3V3Show
    DHT22 DAT (OUT)GPIO 4Show
    DHT22 GND (−)GNDShow
    LED long leg220 Ω resistor, then GPIO 19Show
    LED short legGNDShow

    Wire the DHT22 module by the labels printed on it. Modules order their three pins differently.

  2. Get the code and set your Wi-Fi

    I'm using:

    Steps 2 and 3 follow the tool you pick.

    Open in Cirkit Designer

    The project opens with the sketch and its libraries already in it, so there's nothing to install.

    First add ESP32 boards: open Tools → Board → Boards Manager, search for esp32, and install esp32 by Espressif Systems. Then open the Library Manager (1), search for PubSubClient (2), and install the one by Nick O'Leary (3). Install DHT sensor library by Adafruit the same way; when it asks about dependencies, install them all.

    ESP32 Dev ModuleLIBRARY MANAGERPubSubClientType: AllTopic: AllPubSubClientby Nick O'LearyA client library for MQTTmessaging.More infoINSTALL123

    Then copy the sketch into a new one:

    Set your network: change WIFI_NAME and WIFI_PASSWORD at the top of the sketch to your Wi-Fi's. CirkitWifi is the network inside Cirkit's simulation; a real board can't see it. How the sketch works is in what the code does, above.

  3. Upload and check it

    Plug in your ESP32. In Cirkit, open the Build tab, then Upload firmware: click Select Port and pick your ESP32, then Upload to Device. The first time, Cirkit asks you to install Cirkit Create Agent, a small desktop helper that lets it reach the board over USB. Then open Upload output and serial monitor and click Start Serial Monitor.

    Show me where to click in Cirkit
    ESP32 MQTTFileEditExportHelp
    DesignCodeSimulateBuild
    1Parts & purchasing2Assemble3Upload firmware
    ESP32 Dev ModuleEdit Code

    Board

    ESP32 Dev Module Change

    2

    Port

    Select PortCOM4 Connected

    3

    Upload

    Upload to DeviceUploading...Upload successful

    4

    Check that it works

    Your project should now run as designed.

    Upload output and serial monitor
    Compile / Upload Output
    Device SerialStop

    Read serial data from your device.

    Start Serial Monitor
    Listening on COM4 at 115200 baud
    Connecting to HomeWiFi
    Wi-Fi connected, IP address 192.168.1.42
    Channel: cirkit-learn/7f3a9c21e04b5d88
    Connecting to mqtt.cirkitdesigner.com
    Connected to the broker
    Sent 24.1 C, 48.0 %
    Sent 24.1 C, 48.2 %
    LED on
    Select port

    Select a device port

    Select the device port for uploading code and serial communications

    COM4 (ESP32 Dev Module)
    1. Open Build
    2. Choose Upload firmware
    3. Click Select Port
    4. Pick COM4 (ESP32 Dev Module)
    5. Click Upload to Device
    6. Open Upload output and serial monitor
    7. Click Start Serial Monitor

    In the Arduino IDE, choose ESP32 Dev Module and its port from the board menu, press Upload, then open the Serial Monitor and set it to 115200 baud.

    Show me where to click in the Arduino IDE
    Select BoardESP32 Dev Module

    Select other board and port

    ESP32 Dev ModuleCOM4
    esp32_mqtt.ino
    // ESP32 MQTT: send a DHT22's readings to a broker every 5 s,
    // and switch an LED when an "on" or "off" message arrives.
    #include <WiFi.h>
    #include <PubSubClient.h>
    #include <DHT.h>
    
    OutputSerial Monitor115200 baud

    Compiling sketch...

    Uploading...

    Connecting to HomeWiFi

    Wi-Fi connected, IP address 192.168.1.42

    Channel: cirkit-learn/7f3a9c21e04b5d88

    Connecting to mqtt.cirkitdesigner.com

    Connected to the broker

    Sent 24.1 C, 48.0 %

    Sent 24.1 C, 48.2 %

    LED on

    Done uploading.

    1. Click the board menu
    2. Pick ESP32 Dev Module on COM4
    3. Click Upload
    4. Wait for Done uploading
    5. Click Serial Monitor
    6. Check it is set to 115200 baud

    Then follow it from your phone. Copy the channel the Serial Monitor prints (it changes every time the board starts). On your phone, open HiveMQ's browser client, which connects to any broker, or any MQTT app:

    1. Connect to mqtt.cirkitdesigner.com: port 443 with SSL on in the browser client, which adds the path /mqtt itself; port 1883 in most apps.
    2. Subscribe to <channel>/#.
    3. Publish on to <channel>/led, with retain off.

    It works when:

    • The Serial Monitor shows your network, the board's address, its channel and Connected to the broker.
    • A Sent line follows every five seconds, and the same readings arrive on your phone.
    • Publishing on lights the LED, the Serial Monitor prints LED on, and your phone gets on on …/led/state.

    Not working? See troubleshooting.

    Next guideChoosing a sensor? DHT11 vs DHT22The DHT22 this guide uses against the DHT11: range, accuracy and wiring, both running side by side.

Troubleshooting

Find what the Serial Monitor shows; the checks under it run from the most common cause down.

It stops at "Connecting to" your network

  • WIFI_NAME and WIFI_PASSWORD are exactly your network's. Copy them rather than retyping.
  • The network is 2.4 GHz. The ESP32's Wi-Fi is 2.4 GHz only; if your router has separate 2.4 and 5 GHz networks, use the 2.4 GHz one.
  • The network has no sign-in page. Networks that ask you to sign in in a browser (hotels, some schools) don't work: the sketch can't fill it in.

"Broker connection failed, state …"

  • State -2: the board can reach the broker. It couldn't open a connection: check the broker's name in BROKER, and that your network lets connections out to port 1883.
  • State -4: the broker answers in time. It didn't: the connection is too slow, or the broker is busy. The sketch tries again after five seconds.
  • State 5: the broker accepts the board. It refused it: the broker wants a login (see use your own broker).

"No reading from the DHT22"

  • DAT is on GPIO 4. Check the three wires against the wiring table.
  • The DHT22 runs from 3V3, and VCC and GND aren't swapped. Go by the labels on the module.

The board says "Sent", but nothing arrives on my phone

  • The phone is connected to the same broker, mqtt.cirkitdesigner.com.
  • The channel is the current one. It changes every time the board starts: copy it again.
  • The topic is exact. Topics are case-sensitive: <channel>/#, with the slash.

The LED doesn't switch, and the board prints nothing

  • The message is exactly on or off, lowercase, published to <channel>/led.
  • Retain is off. Cirkit's broker disconnects a client that publishes a retained message.

Nothing in the Serial Monitor

  • The Serial Monitor is set to 115200 baud.

No port appears for the ESP32

  • The cable carries data. The board's USB port carries its serial link as well as power, so a cable that only charges powers the board but shows no port.
  • The board's USB-to-serial chip has its driver. Its name, such as CP210x, is printed on the chip near the USB socket. The driver usually installs itself; if no port appears, install it from the chip's maker (Silicon Labs for a CP210x).

The upload stops at "Connecting..." and says "Failed to connect"

  • The board is in download mode. Hold BOOT, press and release EN (RST on some boards), then release BOOT, and upload again.

"PubSubClient.h": No such file or directory

Arduino IDE only
  • PubSubClient is installed. Install the one by Nick O'Leary from the Library Manager, as in get the code.

Make it yours

Use your own broker

For anything private, use a broker that needs a login, on your own network or hosted. Change the broker's address, and pass the login when connecting:

Changes in esp32_mqtt.ino
const char* BROKER = "192.168.1.20";  // your broker
const int BROKER_PORT = 1883;

// in connectToBroker(), if it wants a login:
if (mqtt.connect(clientId.c_str(), "user", "password")) {

A login alone isn't encryption: on port 1883 the login and readings travel as plain text. Over the internet, use a broker's TLS port, 8883, with the ESP32's encrypting client, NetworkClientSecure, in place ofWiFiClient, given the broker's CA certificate with setCACert().

Send longer messages

PubSubClient's messages, topic and header included, are limited to 256 bytes by default. For a longer message, such as several readings in one JSON object, make room in setup():

In setup()
mqtt.setBufferSize(512);  // before connecting

Send more readings

Add a topic per reading, like topic("pressure"), and publish it beside the others. A subscriber to<channel>/# gets it with no change.

FAQ

Is MQTT secure?

Not by itself. On port 1883 messages travel unencrypted, and a public broker lets anyone subscribe. For private data, use a broker with a login and TLS; see use your own broker.

What's the difference between QoS 0, 1 and 2?

QoS 1 delivers a message at least once, and QoS 2 exactly once; QoS 0, which this sketch uses, isat most once.

Can I use a broker on my own network, such as Mosquitto on a Raspberry Pi?

Yes, if it accepts plain MQTT on port 1883: change BROKER, and add the login if it needs one, as inuse your own broker. A broker that only accepts TLS needs the encrypting client too.

Can I send JSON?

Yes: publish the JSON text as the message. Keep it under PubSubClient's 256 bytes, or raise the limit as insend longer messages.

Why does the channel change every time?

So boards following this guide don't use the same topics on the same public broker. For your own project, a fixed name you choose works just as well.

Simulating ESP32 MQTT in Cirkit Designer

Cirkit runs the ESP32's real firmware: the same sketch, PubSubClient 2.8 and the ESP32's Wi-Fi stack. The board joins a simulated Wi-Fi network, CirkitWifi, with no password, and its connections go out to the internet through Cirkit's servers, so it reaches a real broker.

Cirkit's DHT22 reports exactly the temperature and humidity you set with the sliders, with no measurement error or lag, and refuses a reading taken less than two seconds after the last one, as its datasheet asks. Cirkit doesn't simulate radio signal strength or a crowded network, and timings, such as how long the round trip takes, depend on Cirkit's servers rather than your router.

References