MQTT Bare Minimum Sketch for ESP8266

Introduction: MQTT Bare Minimum Sketch for ESP8266

If you are new to MQTT and you want a simple example to start with, this is for you. This example uses CloudMQTT to run a very simple sketch in a ESP8266 ESP-01 module that publishes and subscribes a led status that you may use for your more complex projects. Simple put it, is a Bare Minimum for your own sketches!

Teacher Notes

Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.

Step 1: Create a MQTT Cloud Account and an Instance

You may use a MQTT account from many provider or you may install a Mosquitto server by yourself, however here we will use the already available server To create an accont follow these steps:

  1. Go to and select Plans;
  2. Select the Free plan Cute Cat;
  3. Follow all steps until you get into the Control Panel;
  4. Press in the +Create Button to create an Instance;
  5. Give a name to your Instance and press Create;
  6. Write down the following Instance info:
    • Server
    • Port

Step 2: Create Users and Rules

While in the Instance window, follow this steps:

  1. Create an user with the username "light" and the password "12345";
  2. Create two new rules for the user "light" with the topic "/light/in" and "/light/out" checking Read and Write access;
  3. Write down the following user and rule info:
    • Username
    • Password
    • Topics

Step 3: Add ESP8266 Board to the Arduino IDE

To be able to upload sketches to your ESP8266 board, you have to add it to your Arduino IDE, to do so follow these steps:

  1. Go to File->Preferences;
  2. Enter the address "" in Aditional Boards Manager;
  3. Go to Tools->Board->Boards Manager...;
  4. Filter by esp8266, select the board esp8266 and press Install;
  5. In Tools->Board select the Generic ESP8266 Module.

Step 4: Add PubSubClient Library to the Arduino IDE

The PubSubClient Library allows you to communicate with the MQTT Server, so to install it follow these steps:

  1. Go to Sketch->Include Library->Manage Libraries...;
  2. Filter by pubsubclient, select the library PubSubClient and press Install.

Step 5: Wire Your ESP8266 ESP-01 to Enable Uploading

Wire your ESP8266 as shown, note that the C1 capacitor is there to maintain the voltage stable and C2 to allow Serial Monitor. If you aren't able to use the Serial Monitor, connect R1 to GPIO2 instead, this will free the GPIO0 and any trouble that it may give. After Uploading you have to disconnect GPIO0 from GND to run the sketch (IO)!

If you feel bold, use my definitive wiring instead, see here:

Step 6: Copy and Past MQTT Bare Minimum Sketch

Here is the Bare Minimum code, change the variables accordingly to your credentials:

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

#define wifi_ssid "ssid" #define wifi_password "password"

#define mqtt_server "address" #define mqtt_port port #define mqtt_user "light" #define mqtt_password "12345"

#define in_topic "/light/in" #define out_topic "/light/out" // Replace by 2 if you aren't enable to use Serial Monitor... Don't forget to Rewire R1 to GPIO2! #define in_led 0

WiFiClient espClient; PubSubClient client;

void setup() { Serial.begin(115200); setup_wifi(); client.setClient(espClient); client.setServer(mqtt_server, mqtt_port); client.setCallback(callback); // initialize digital pin LED_BUILTIN as an output. pinMode(in_led, OUTPUT); digitalWrite(in_led, HIGH); }

void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(wifi_ssid);

WiFi.begin(wifi_ssid, wifi_password);

while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }

Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); }

void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect // If you do not want to use a username and password, change next line to // if (client.connect("ESP8266Client")) { if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }

void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { char receivedChar = (char)payload[i]; Serial.print(receivedChar); if (receivedChar == '0') digitalWrite(in_led, LOW); if (receivedChar == '1') digitalWrite(in_led, HIGH); } Serial.println(); }

void loop() { if (!client.connected()) { reconnect(); } client.loop(); // Publishes a random 0 and 1 like someone switching off and on randomly (random(2)) client.publish(out_topic, String(random(2)).c_str(), true); delay(1000); client.subscribe(in_topic); delay(1000); }

Adjust the "in_led" value to 2 if you wish to use Serial Monitor!

Step 7: Test Your Sketch

After Uploading the Sketch, disconnect the IO wire and test it following these steps:

  1. In your CloudMQTT instance go to Websocket UI;
  2. Confirm that you are receiving 0 and 1 in the topic "/light/out";
  3. Send 0 to the topic "/light/in" and confirm that the LED in your board turns off;
  4. Send 1 to the topic "/light/in" and confirm that the LED in your board turns on.

If you have any trouble please comment...

Be the First to Share


    • Magnets Challenge

      Magnets Challenge
    • Raspberry Pi Contest 2020

      Raspberry Pi Contest 2020
    • Wearables Contest

      Wearables Contest

    4 Discussions


    5 weeks ago

    Funcionou 100%, parabéns pelo tutorial!


    Question 11 months ago

    The sketch is "BareMinimum":
    I have gotten message like this"Attempting MQTT connection...failed, rc=-2 try again in 5 seconds". I have checked the server "" and password. I am not sure about the (port defination (port, ssl port or websockets port)?


    Question 1 year ago on Step 6


    Nice instructables, however I have 2 questions:

    1. who is: ESP8266Client from the line

    if (client.connect("ESP8266Client"))

    2. Also, I tried to update the code to work with ThingsBoard demo account, but I have no luck I get in the serial window an RC=-2 code when Attempting an MQTT connection. Can you please update the code also for a demo account on ThingsBoard... ?


    1 year ago

    I was able to compile this on an ESP32 by changing the line

    #include <ESP8266WiFi.h>


    #include <WiFi.h>

    Was able to install PubSubClient on ESP32 without errors using arduino dev IDE. Saw somewhere it _apparently_ works on ESP32.

    Was not able to connect to the MQTT Cloud server. Was anyone able to connect to MQTTCLOUD using ESP32?