Quick answer: to control an LED on a NodeMCU ESP8266 with MQTT, install the ESP8266 board package and the PubSubClient library in the Arduino IDE, connect the board to Wi-Fi, connect to a broker (Mosquitto on a Raspberry Pi, or a public test broker), subscribe to a command topic such as solderhub/lab/nodemcu01/command/led, and in the callback set the GPIO HIGH for ON and LOW for OFF. Then publish the applied state to a separate, retained state topic so dashboards always show the real LED state. The complete sketch is below; test it with mosquitto_pub or the free MQTTX app before you build a dashboard.
This tutorial goes a step further than most "MQTT LED on/off" examples: it separates command and state topics, rejects bad payloads, reports online/offline status with MQTT Last Will, reconnects without blocking, and lists the problems you are most likely to hit. Everything runs on 3.3 V, so it is a safe first MQTT project before you move on to relays.
| What you need | Notes |
|---|---|
| NodeMCU ESP8266 (v2 or v3) or Wemos D1 mini | Any ESP8266 board with the Arduino core works |
| 5 mm LED + 220–330 Ω resistor | Or use the onboard LED (GPIO2, active-low) |
| Breadboard, jumper wires, micro-USB data cable | A charge-only cable will not upload |
| MQTT broker | Mosquitto on a Raspberry Pi/PC, or a public test broker for a first try |
| MQTT client for testing | mosquitto_pub / mosquitto_sub, or MQTTX (desktop GUI) |
How the message flow works
- A controller (terminal, MQTTX, Node-RED, Home Assistant) publishes
ONorOFFto the command topic. - The broker forwards it to every subscriber of that topic, including the NodeMCU.
- The NodeMCU's callback checks the payload, sets the GPIO, and publishes the applied state to the state topic with the retained flag.
- Any dashboard subscribed to the state topic updates, and a dashboard that connects later receives the retained state immediately.
| Topic | Who publishes | Payload | Retained? |
|---|---|---|---|
solderhub/lab/nodemcu01/command/led | Controller | ON / OFF | No: a stale ON must not replay after a reboot |
solderhub/lab/nodemcu01/state/led | NodeMCU | ON / OFF | Yes: new dashboards see the current state |
solderhub/lab/nodemcu01/status | NodeMCU (and broker via Last Will) | online / offline | Yes |
Wiring the LED
| NodeMCU pin | GPIO | Connects to |
|---|---|---|
| D5 | GPIO14 | 330 Ω resistor → LED anode (long leg) |
| GND | – | LED cathode (short leg, flat side) |
With a 3.3 V output and a typical red LED (about 2 V forward voltage), 330 Ω gives roughly 4 mA, which is bright enough and well within the ESP8266's pin limits. D5 is a safe choice because it has no boot-strapping role. Avoid D3 (GPIO0), D4 (GPIO2) and D8 (GPIO15) for external LEDs: they must be at specific levels at power-up, and a wrong load can stop the board from booting. See the NodeMCU ESP8266 pinout for the full list.
No LED handy? Use the onboard LED: set LED_PIN to LED_BUILTIN (GPIO2) and invert the logic, because it lights when the pin is LOW.
1. Get a broker running
You have two options:
| Option | Good for | Watch out |
|---|---|---|
Public test broker (test.mosquitto.org or broker.emqx.io, port 1883) | A two-minute first test without installing anything | Not private: anyone can read and publish to your topics. Use a unique topic prefix and never send anything that matters |
| Your own Mosquitto on a Raspberry Pi or PC | Real projects, dashboards, home automation | Mosquitto 2.x listens only on localhost until you add a listener and authentication |
For your own broker, follow Install Mosquitto on Raspberry Pi 5 (the same steps work on other Pi models and Debian/Ubuntu), then create a user for the NodeMCU. If the board can't connect, the most common cause is that Mosquitto 2.x refuses remote clients by default. A minimal LAN config in /etc/mosquitto/conf.d/lan.conf:
listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwdCreate the user and restart:
sudo mosquitto_passwd -c /etc/mosquitto/passwd nodemcu01
sudo systemctl restart mosquitto(For a quick, insecure lab-only test you can use allow_anonymous true instead, but switch back before the broker is reachable from anywhere you don't trust.) You can check the broker end to end without any hardware using Test MQTT without hardware.
2. Upload the NodeMCU sketch
- In the Arduino IDE, add the ESP8266 board package (see installing ESP8266 in the Arduino IDE) and select NodeMCU 1.0 (ESP-12E Module).
- Open Library Manager, search for PubSubClient and install the one by Nick O'Leary.
- Paste the sketch, fill in your Wi-Fi name, password, broker IP and MQTT user, and upload.
- Open the Serial Monitor at 115200 baud. You should see the IP address, then
MQTT connected.
The sketch never blocks in loop(): if Wi-Fi or the broker drops, it retries every 5 seconds and keeps running. It also registers a Last Will so the broker announces offline if the board loses power.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// ---- Your settings (keep real passwords out of public repos) ----
const char* WIFI_SSID = "REPLACE_WITH_WIFI";
const char* WIFI_PASSWORD = "REPLACE_WITH_WIFI_PASSWORD";
const char* MQTT_HOST = "192.168.1.50"; // broker IP, or "test.mosquitto.org"
const uint16_t MQTT_PORT = 1883;
const char* MQTT_USER = "nodemcu01"; // "" for an anonymous/public broker
const char* MQTT_PASSWORD = "REPLACE_WITH_MQTT_PASSWORD";
const char* CLIENT_ID = "solderhub-nodemcu01"; // must be unique on the broker
const char* COMMAND_TOPIC = "solderhub/lab/nodemcu01/command/led";
const char* STATE_TOPIC = "solderhub/lab/nodemcu01/state/led";
const char* STATUS_TOPIC = "solderhub/lab/nodemcu01/status";
const uint8_t LED_PIN = D5; // GPIO14
const bool LED_ACTIVE_LOW = false; // true for the onboard LED (LED_BUILTIN)
WiFiClient net;
PubSubClient mqtt(net);
bool ledOn = false;
unsigned long lastAttempt = 0;
void applyLed(bool on) {
ledOn = on;
digitalWrite(LED_PIN, (on != LED_ACTIVE_LOW) ? HIGH : LOW);
mqtt.publish(STATE_TOPIC, on ? "ON" : "OFF", true); // retained state
Serial.printf("LED -> %s\n", on ? "ON" : "OFF");
}
void onMessage(char* topic, byte* payload, unsigned int length) {
if (strcmp(topic, COMMAND_TOPIC) != 0) return;
char msg[8];
if (length >= sizeof(msg)) return; // too long to be ON/OFF
memcpy(msg, payload, length);
msg[length] = '\0';
if (strcasecmp(msg, "ON") == 0) applyLed(true);
else if (strcasecmp(msg, "OFF") == 0) applyLed(false);
else Serial.printf("Ignored payload: %s\n", msg);
}
bool connectMqtt() {
bool ok = (strlen(MQTT_USER) > 0)
? mqtt.connect(CLIENT_ID, MQTT_USER, MQTT_PASSWORD, STATUS_TOPIC, 1, true, "offline")
: mqtt.connect(CLIENT_ID, STATUS_TOPIC, 1, true, "offline");
if (!ok) {
Serial.printf("MQTT failed, rc=%d\n", mqtt.state());
return false;
}
Serial.println("MQTT connected");
mqtt.publish(STATUS_TOPIC, "online", true);
mqtt.subscribe(COMMAND_TOPIC);
mqtt.publish(STATE_TOPIC, ledOn ? "ON" : "OFF", true);
return true;
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LED_ACTIVE_LOW ? HIGH : LOW); // start OFF
WiFi.mode(WIFI_STA);
WiFi.setAutoReconnect(true);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED && millis() < 20000) { delay(250); Serial.print("."); }
Serial.println();
if (WiFi.status() == WL_CONNECTED) Serial.println(WiFi.localIP());
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setCallback(onMessage);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) return; // auto-reconnect handles Wi-Fi
if (!mqtt.connected()) {
if (millis() - lastAttempt > 5000) {
lastAttempt = millis();
connectMqtt();
}
return;
}
mqtt.loop(); // must run often: receives messages and sends keepalives
}What the important lines do
| Code | Why it matters |
|---|---|
mqtt.connect(..., STATUS_TOPIC, 1, true, "offline") | Registers a retained Last Will. If the board vanishes, the broker publishes offline for it |
mqtt.subscribe(COMMAND_TOPIC) inside connectMqtt() | Subscriptions are lost on reconnect (clean session), so subscribe again every time |
strcmp / strcasecmp on a fixed buffer | Avoids String heap churn on the ESP8266 and ignores anything that isn't ON or OFF |
mqtt.publish(STATE_TOPIC, ..., true) | Retained state: a dashboard that opens later sees the LED's real state at once |
mqtt.loop() every pass | Without it, no messages arrive and the broker drops the client after the keepalive (15 s by default) |
mqtt.state() in the log | Tells you why a connection failed (see the troubleshooting table) |
3. Test it from a terminal or MQTTX
In one terminal, watch everything the board reports (the # wildcard covers status and state):
mosquitto_sub -h 192.168.1.50 -u nodemcu01 -P 'YOUR_PASSWORD' -t 'solderhub/lab/nodemcu01/#' -vIn a second terminal, switch the LED on and off:
mosquitto_pub -h 192.168.1.50 -u nodemcu01 -P 'YOUR_PASSWORD' -t 'solderhub/lab/nodemcu01/command/led' -m 'ON'
mosquitto_pub -h 192.168.1.50 -u nodemcu01 -P 'YOUR_PASSWORD' -t 'solderhub/lab/nodemcu01/command/led' -m 'OFF'Expected output in the first terminal:
solderhub/lab/nodemcu01/status online
solderhub/lab/nodemcu01/state/led OFF
solderhub/lab/nodemcu01/command/led ON
solderhub/lab/nodemcu01/state/led ONNow unplug the NodeMCU. After roughly one and a half keepalive periods (about 20–25 seconds) the broker publishes status offline for it: that is the Last Will working.
Prefer a GUI? In MQTTX, create a connection with the same host, port and user, subscribe to solderhub/lab/nodemcu01/#, and publish ON to the command topic. On a public broker, drop the -u/-P options and use a topic prefix nobody else will guess.
Retained messages, QoS and safety
- State is retained, commands are not. A retained ON command would switch the LED (or a relay) on again every time the board reconnects, even hours later.
- PubSubClient subscribes at QoS 0 by default and publishes only at QoS 0. For an LED that is fine: the retained state tells you whether the command arrived. If you need QoS 1 delivery for incoming commands, use
mqtt.subscribe(topic, 1)and make the handler idempotent (ON twice = ON). - Explicit ON/OFF beats TOGGLE. A repeated or duplicated TOGGLE flips the output the wrong way; a repeated ON does nothing harmful.
- Before switching anything bigger, check the relay module's input polarity (many are active-low), its rating, and what state it takes at boot and when the board is offline. Never wire mains on a breadboard, and never rely on an MQTT message as the only safety interlock.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
MQTT failed, rc=-2 | Broker unreachable: wrong IP, firewall, or Mosquitto 2.x listening on localhost only | Ping the broker IP; add listener 1883 to the config; open port 1883 on the host firewall |
rc=5 (not authorised) | Wrong user/password, or anonymous access disabled | Recreate the user with mosquitto_passwd; check the password file path in the config |
rc=4 (bad credentials) | Username or password rejected | Re-type both; watch for trailing spaces |
rc=2 (bad client ID) | Broker rejected the client ID | Use a short, plain client ID |
| Connects, then drops every few seconds | Two devices using the same client ID | Give every device a unique CLIENT_ID |
| Connected, but no reaction to commands | Topic mismatch (case, slash, typo) or mqtt.loop() not called | Subscribe to solderhub/# in a terminal to see exactly what is published |
| Serial shows "LED -> ON" but LED stays dark | LED reversed, wrong pin, or missing GND | Long leg to the resistor/GPIO side; check D5 = GPIO14 on your board |
| Onboard LED works "backwards" | GPIO2 LED is active-low | Set LED_ACTIVE_LOW = true |
| Board won't boot with the LED fitted | LED on D3, D4 or D8 (boot pins) | Move it to D5, D6 or D7 |
| Larger JSON payloads never arrive | PubSubClient's default 256-byte buffer | Call mqtt.setBufferSize(512) before connecting |
| Never gets an IP address | 5 GHz network or wrong password | The ESP8266 supports 2.4 GHz only |
Full list of return codes and fixes: MQTT troubleshooting: connection refused, rc=-2 and rc=5. For flaky Wi-Fi, see the ESP8266 Wi-Fi reconnect guide.
FAQ
Do I need a Raspberry Pi for MQTT?
No. For a first test, a public broker such as test.mosquitto.org works. For anything you rely on, run Mosquitto on a Pi, a PC, a NAS or Home Assistant, so your messages stay on your network.
Which library is best for MQTT on the ESP8266? PubSubClient is the simplest and most widely used. AsyncMqttClient supports QoS 1/2 publishing and is non-blocking, but it needs extra async TCP libraries and is harder for beginners.
Can I control the LED from my phone?
Yes. Any MQTT app (for example MQTT Dash or IoT MQTT Panel on Android) can publish ON/OFF to the command topic. From outside your home network you need a broker you can reach securely, ideally with TLS.
Why is my LED state wrong after a reboot? The sketch starts with the LED OFF and publishes OFF. If you want it to restore the last state, subscribe to the state topic at startup and apply the retained value, or store it in EEPROM/LittleFS.
Does the same code work on an ESP32?
Almost. Replace #include <ESP8266WiFi.h> with #include <WiFi.h>, pick a valid ESP32 GPIO, and it runs. See the ESP32 MQTT publish/subscribe tutorial.
Is MQTT on port 1883 secure? No. It is unencrypted. Fine on a trusted LAN; use TLS (usually port 8883) over the internet.
Next steps
- Add a dashboard button: Control an ESP32 LED with Node-RED and MQTT, which uses the same topic pattern.
- Understand the protocol: MQTT explained: broker, topics, QoS, retained messages and Last Will.
- Name topics well before the project grows: MQTT topic naming best practices.
- Make reconnects bulletproof: Non-blocking MQTT auto-reconnect (written for ESP32; the pattern is the same on ESP8266).
- Prefer no code on the dashboard side? Try NodeMCU ESP8266 with Blynk.
Official references: Mosquitto documentation and the PubSubClient API.




