NodeMCU ESP8266 to ioBroker, connect relay via MQTT

In this tutorial, I will show you how to make simple smart devices with an ESP8266 NodeMCU using the Arduino framework and integrate them into ioBroker via MQTT.

Difficulty: Intermediate

Technically reviewed: October 2026

Development board: ESP8266 NodeMCU

This tutorial uses an ESP8266 NodeMCU, but you can also use another microcontroller, such as an ESP32. In that case, check its pinout and voltage levels, change the pins in the Arduino sketch, and use libraries suitable for your board.


You only need a few parts for the circuit:

  • ESP8266 NodeMCU
  • LED and, for the second example, a relay module
  • 330 Ω resistor
  • Jumper wires
  • Breadboard

The LED circuit

A simple LED circuit is enough to build and test the Arduino sketch. It also makes the switching behaviour easy to see. You can assemble the circuit on a breadboard or solder the LED and resistor directly to a jumper wire that fits the microcontroller pin.

Connect the LED anode (+) to the NodeMCU D1 pin through a 330 Ω resistor. Connect the cathode (−) to a GND pin on the NodeMCU.

A computer USB port can supply enough power for this LED circuit. If you use an external power supply, check its polarity, voltage and available current.

ESP8266 NodeMCU connected to an LED through a resistor
ESP8266 NodeMCU with the connected LED.

Arduino sketch for switching the LED

Install the ESP8266 board package and the PubSubClient library in the Arduino IDE. Then upload the following sketch to the NodeMCU.

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

constexpr char ssid[] = "mySSID";
constexpr char password[] = "myPassword";
constexpr char mqtt_server[] = "192.168.1.23";
constexpr char clientId[] = "ESP8266-LedTest";

constexpr uint16_t ledPin = 5;  // GPIO5 -> D1

unsigned long lastReconnectAttempt = 0;
unsigned long lastWifiReconnectAttempt = 0;

WiFiClient espClient;
PubSubClient client(espClient);


void reconnect() 
{
  Serial.println(F("Connecting to the MQTT server..."));
  if(!client.connected()) 
  {
    if(client.connect(clientId))
    {
      Serial.println(F("MQTT server is connected!"));
      client.subscribe("test/led");
    } 
    else 
    {
      Serial.print(F("MQTT connection failed, retrying in 5 seconds"));
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length)
{
  if(strcmp(topic, "test/led") == 0)
  {
    if(strncmp((char*)payload, "false", length) == 0 && length == 5)
    {
      digitalWrite(ledPin, LOW);
      Serial.println(F("Led is off!"));
    } 
    else if(strncmp((char*)payload, "true", length) == 0 && length == 4)
    {
      digitalWrite(ledPin, HIGH);
      Serial.println(F("Led is on!"));
    }
  }
}

void setup() 
{
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  
  Serial.begin(115200);
  delay(500);

  Serial.println();
  Serial.println(F("Connecting to the wifi network..."));
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while(WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(F("."));
  }
  Serial.println();
  Serial.println(F("Wifi is connected!"));

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

void loop() 
{
  unsigned long now = millis();

  if(WiFi.status() != WL_CONNECTED)
  {
    if(now - lastWifiReconnectAttempt > 5000)
    {
      lastWifiReconnectAttempt = now;
      Serial.println(F("WiFi connection lost! Reconnecting..."));
      WiFi.disconnect();
      WiFi.begin(ssid, password);
    }
    return;
  }

  if(!client.connected()) 
  {
    if(now - lastReconnectAttempt > 5000)
    {
      lastReconnectAttempt = now;
      reconnect();
    }
  }
  else
  {
    client.loop();
  }
}

How does the LED sketch work?

First, the sketch configures the NodeMCU D1 pin as an output and switches the LED off. It then connects to the specified Wi-Fi network. You can follow the connection process in the Serial Monitor set to 115200 baud.

Once Wi-Fi is available, the NodeMCU connects to the MQTT broker and subscribes to the test/led topic. Think of this as listening for messages sent to that topic. The LED only changes state when a suitable command arrives there.

The true message sets D1 HIGH. Current flows through the 330 Ω resistor and the LED, so the LED lights up. The false message sets D1 LOW and the LED turns off. The sketch checks the MQTT topic first, then the message content and its length. Messages sent to another topic, or messages with other content, do not switch the LED.

The loop() function keeps the MQTT connection running. If it drops, the NodeMCU tries to reconnect about every five seconds and subscribes to test/led again after a successful connection. If Wi-Fi disconnects, the sketch attempts to reconnect and pauses MQTT communication until Wi-Fi is available again.

A lost connection does not issue a new switching command, so the LED remains in its last state. The Serial Monitor messages can help you tell whether the problem is with Wi-Fi or MQTT.

Switching a relay module instead of the LED

An ESP8266 NodeMCU GPIO pin cannot drive a relay coil directly, so a driver circuit is needed between them. Choose a relay module that includes such a circuit. It may use a transistor, a FET or an optocoupler as part of the driver.

You can also use a module with several relays to switch several devices. Each relay has its own IN control input, which needs a separate GPIO connection.

Warning!

The following example switches a device powered by mains voltage. Mains voltage can cause serious injury, fatal electric shock or fire.

Always disconnect power before working on the circuit. Pay particular attention to protection against accidental contact at all mains wiring and connections. Parts carrying mains voltage must be enclosed in a suitable electrical enclosure.

Use insulated cable, a lamp holder and a plug suitable for the mains voltage and the load.

Only work with mains voltage if you have the necessary knowledge. I cannot accept responsibility for damage or injury. If you are unsure, ask a qualified electrician for help.

A relay can have two or three terminals on its contact side. A two-terminal relay may provide COM–NC or COM–NO contacts. A three-terminal relay provides NC, COM and NO contacts.

  • COM (common) is the shared contact. In this example, the live conductor is connected here.
  • NC (normally closed) is connected to COM while the relay is at rest. When the relay energizes, the COM–NC connection opens.
  • NO (normally open) is disconnected from COM while the relay is at rest. When the relay energizes, the COM–NO connection closes and current can flow through the connected circuit.

Warning!

The solder joints for the relay contacts on the underside of the module’s circuit board may carry mains voltage. Touching these areas can be fatal. Place the relay module in a suitably sized, closed electrical enclosure before applying power.

For this example, connect the NodeMCU GPIO5 (D1) pin to the relay module’s IN1 input. The relay module used here switches on when its IN1 input is pulled LOW.

We use the relay’s NO contact, so the digitalWrite(relayPin, LOW); line in the Arduino sketch switches the lamp on.

Relay module pinESP8266 NodeMCU pin
GND — common groundGND
VCC — driver circuit supply3.3 V
JD-VCC — relay coil supplyVIN (5 V)
IN1 — driver control inputD1

The conceptual diagram below shows the circuit, and the table above helps identify the connections. Relay modules can have different pin arrangements, so check the documentation for your particular module before wiring it. A suitably rated relay can also switch other mains-powered loads, provided the complete circuit is designed for that load.

Conceptual circuit diagram with a NodeMCU ESP8266, relay module and 230 V lamp
Conceptual circuit diagram with a NodeMCU ESP8266, relay module and 230 V lamp.

Arduino sketch for controlling the relay

Upload the following sketch to the NodeMCU for the relay circuit.

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

constexpr char ssid[] = "mySSID";
constexpr char password[] = "myPassword";
constexpr char mqtt_server[] = "192.168.1.23";
constexpr char clientId[] = "ESP8266-RelayTest";

constexpr uint16_t relayPin = 5;  // GPIO5 -> D1

unsigned long lastReconnectAttempt = 0;
unsigned long lastWifiReconnectAttempt = 0;

WiFiClient espClient;
PubSubClient client(espClient);


void reconnect() 
{
  Serial.println(F("Connecting to the MQTT server..."));
  if(!client.connected()) 
  {
    if (client.connect(clientId))
    {
      Serial.println(F("MQTT server is connected!"));
      client.subscribe("test/relay");
    } 
    else 
    {
      Serial.print(F("MQTT connection failed, retrying in 5 seconds"));
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length)
{
  if(strcmp(topic, "test/relay") == 0)
  {
    if(strncmp((char*)payload, "false", length) == 0 && length == 5)
    {
      digitalWrite(relayPin, HIGH);
      Serial.println(F("Light is off!"));
    } 
    else if(strncmp((char*)payload, "true", length) == 0 && length == 4)
    {
      digitalWrite(relayPin, LOW);
      Serial.println(F("Light is on!"));
    }
  }
}

void setup() 
{
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, HIGH);
  
  Serial.begin(115200);
  delay(500);

  Serial.println();
  Serial.println(F("Connecting to the wifi network..."));
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(F("."));
  }
  Serial.println();
  Serial.println(F("Wifi is connected!"));

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

void loop() 
{
  unsigned long now = millis();

  if(WiFi.status() != WL_CONNECTED)
  {
    if(now - lastWifiReconnectAttempt > 5000)
    {
      lastWifiReconnectAttempt = now;
      Serial.println(F("WiFi connection lost! Reconnecting..."));
      WiFi.disconnect();
      WiFi.begin(ssid, password);
    }
    return;
  }

  if(!client.connected()) 
  {
    if(now - lastReconnectAttempt > 5000)
    {
      lastReconnectAttempt = now;
      reconnect();
    }
  }
  else
  {
    client.loop();
  }
}

How is the relay version different?

The overall structure is much like the LED example, but there are a few important differences. These are two separate sketches: upload the one that matches the circuit you are using to the ESP8266 NodeMCU.

The NodeMCU connects to Wi-Fi and the MQTT broker and then listens for commands. This time it subscribes to test/relay, and D1 controls the relay module’s IN1 input instead of an LED.

The relay module in this example is active LOW, so the output levels have the opposite meaning from the LED circuit. A true command sets D1 LOW. The relay energizes, its COM and NO contacts close, and the lamp turns on. A false command sets D1 HIGH; the relay releases and the lamp turns off.

At startup, the sketch sets the relay to its off state. Wi-Fi and MQTT connection handling and message checking work in the same way as in the LED example. If the connection drops, the sketch does not change the relay state automatically. After reconnecting, it waits for the next command.


← Further Arduino Tutorials

← More Arduino / ESP Examples and Projects

← More ioBroker Content