MQTT Bare Minimum Sketch for ESP8266

by RuiMonteiro in Circuits > Arduino

23906 Views, 25 Favorites, 0 Comments

MQTT Bare Minimum Sketch for ESP8266

Screenshot from 2015-04-09 16-08-58_2.png

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!

Create a MQTT Cloud Account and an Instance

e-mqttw-38-piww-000.png

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 https://www.cloudmqtt.com. To create an accont follow these steps:

  1. Go to https://www.cloudmqtt.com 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

Create Users and Rules

aae917458ba6e3d17ed6fa94d99d51bd1b6051f5_1_510x500.png

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

Add ESP8266 Board to the Arduino IDE

Preference_json.png

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 "http://arduino.esp8266.com/stable/package_esp8266com_index.json" 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.

Add PubSubClient Library to the Arduino IDE

installing-PubSubClient-for-Arduino.png

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.

Wire Your ESP8266 ESP-01 to Enable Uploading

MQTT_BareMinimum_legend.PNG
FIA7SPTIY4QHNFS.LARGE.jpg

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: https://www.instructables.com/id/FTDI-ESP8266-Definitive-Wiring/

Copy and Past MQTT Bare Minimum Sketch

arduino-upload.gif

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!

Test Your Sketch

CloudMQTT_Console.PNG

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...