Sony Arouje

a programmer's log

MQTT Communication with Arduino using ESP8266 ESP-01

with 100 comments

I was doing some experiments with Arduino connected to WiFi using ESP8266 module. The priority of my experiment was to establish MQTT communication with my local MQTT server and Arduino. I tried so many Arduino libraries for ESP8266 but none of them are compatible with PubSubClient, a good MQTT library for Arduino. Today I come across a library called WiFiEsp, it has similar footprints of Arduino WiFi library, and it can work with PubSubClient. This post deals with how to utilize both PubSubClient and WifiEsp libraries to establish MQTT communication with an MQTT server.

Connecting ESP8266 to Arduino

  • I powered ESP8266 directly from my Arduino’s 5V. You shouldn’t do that, it may damage the wifi module as it deals with 3.3v. This wifi module need more current than Arduino’s 3.3v pin can provide, so connecting Arduino 3.3v to Wifi module will not work. A good option is to connect Arduino 5v to a 3.3v voltage regulator like LM1117/LD117 and power the wifi module from LM*. Connect both VCC and CH_PD pin of ESP to 3.3v power.
  • ESP8266 GND to Arduino GND. If powering ESP externally then Arduino and ESP should have a common GND.
  • ESP8266 TXD to Arduino RXD, in the below sketch I used Softserial and connected to D2.
  • ESP8266 RXD to Arduino TXD. Arduino Pin supply 5v and can damage the wifi module. So I used two resistors to create a voltage divider (Google search and you will get it). In the below sketch I used Softserial and connected to D3.

 

Arduino Sketch

I decided to write a sketch to see the MQTT in action. Below sketch is just a combination of samples provided in WifiEsp and Pubsubclient. I just combined both sample codes to verify the communication, so nothing special. The end result is, Arduino could establish MQTT connection to my MQTT server and send and receive messages for subscribed topics.

 

#include <WiFiEsp.h> #include <WiFiEspClient.h> #include <WiFiEspUdp.h> #include "SoftwareSerial.h" #include <PubSubClient.h> IPAddress server(10, 0, 0, 2); char ssid[] = "XYZ"; // your network SSID (name) char pass[] = "pwd"; // your network password int status = WL_IDLE_STATUS; // the Wifi radio's status // Initialize the Ethernet client object WiFiEspClient espClient; PubSubClient client(espClient); SoftwareSerial soft(2,3); // RX, TX void setup() { // initialize serial for debugging Serial.begin(9600); // initialize serial for ESP module soft.begin(9600); // initialize ESP module WiFi.init(&soft); // check for the presence of the shield if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue while (true); } // attempt to connect to WiFi network while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network status = WiFi.begin(ssid, pass); } // you're connected now, so print out the data Serial.println("You're connected to the network"); //connect to MQTT server client.setServer(server, 1883); client.setCallback(callback); } //print any message received for subscribed topic 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++) { Serial.print((char)payload[i]); } Serial.println(); } void loop() { // put your main code here, to run repeatedly: if (!client.connected()) { reconnect(); } client.loop(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect, just a name to identify the client if (client.connect("arduinoClient")) { Serial.println("connected"); // Once connected, publish an announcement... client.publish("command","hello world"); // ... and resubscribe client.subscribe("presence"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }

 

 

For testing MQTT communication, I wrote a Server and a Client couple of months ago, both are node js apps and can run in my development machine. Server uses Mosca and Client uses MQTT module.

Below is the code for Server and Client.

 

Server

var mosca = require('mosca'); var ascoltatore = { //using ascoltatore type: 'mongo', url: 'mongodb://localhost:27017/mqtt', pubsubCollection: 'ascoltatori', mongo: {} }; var moscaSettings = { port: 1883, backend: ascoltatore, persistence: { factory: mosca.persistence.Mongo, url: 'mongodb://localhost:27017/mqtt' } }; var server = new mosca.Server(moscaSettings); server.on('ready', setup); server.on('clientConnected', function (client) { console.log('client connected', client.id); }); // fired when a message is received server.on('published', function (packet, client) { console.log('Published', packet.payload); }); // fired when the mqtt server is ready function setup() { console.log('Mosca server is up and running'); }

As you can see, server uses Mongodb to persist the client connection, run a mongodb instance before running MQTT server.

Client

var mqtt = require('mqtt'); var client = mqtt.connect('mqtt://10.0.0.2', {clientId:'nodeapp'}); client.on('connect', function () { client.subscribe('command'); client.publish('presence', 'Hello mqtt'); }); client.on('message', function (topic, message) { console.log('from mqtt ' + message.toString()); });

Happy coding…

Written by Sony Arouje

March 15, 2016 at 5:35 pm

Posted in Arduino

Tagged with , ,

100 Responses

Subscribe to comments with RSS.

  1. You have saved me so much searching and pain. Thank-you!

    Sea

    May 2, 2016 at 4:58 pm

    • thanks for leaving your comments.

      Sony Arouje

      May 2, 2016 at 5:09 pm

      • Hey Sony, also in my case you save me with the best working example I found.
        I wanna ask you 1 thing : in my esp, after the subscription to the topic, the blue led on esp blinks out every cycle. Is it normal?

        Muplex

        February 5, 2017 at 4:07 pm

      • The blinking of led is fine i guess. Great to hear my post helped you.

        Sony Arouje

        February 5, 2017 at 6:16 pm

      • Hi Sony,
        It is great work. I do working with the mosquitto server but getting the same issue that the blue led blinks. What is the blue led blinks meaning that the network traffic is high.

        For my case, I can publish once and receive one message and after that, no more message receive but at my other subscribe can receive message.

        Possible due to hug traffic?

        Please help to receive messages and multiple publish.

        jacksonlnm

        October 4, 2017 at 9:12 am

    • I didn’t made it ! 😦

      I don’t know what is problem, I have external power supply of 3v3, and used 2 resistors of 220 ohms for RX&TX on 2D and 3D.

      Arduino IDE has sucessfull compile and upload program to arduino uno.

      what can be problem ?

      Nedim.HX

      March 4, 2017 at 10:19 pm

      • Not sure what is the reason. It’s difficult to assert the issue without seeing the connection schema.

        Sony Arouje

        March 6, 2017 at 3:48 pm

    • Hi Sony,
      I find the reason of the huge traffic. It is due to the client.loop at the loop of arduino. Everytime the client.loop is running, it check any data require to publish or any receive data from subscribe. It just like a polling mechanism to check data by the program. I add delay(200) at the main loop, then the traffic drop significantly and the subscribe data can receive more reliably.

      I think that is not a good approach to poll the data. Is there have any other idea?

      jacksonlnm

      October 4, 2017 at 12:35 pm

  2. wifiESp library work on which firm ware..whats your? and how to update the firmware

    Md Shadab Abedin

    May 3, 2016 at 5:52 pm

    • I am using wifiesp library in Arduino Nano. Not programming wifi device.

      Sony Arouje

      May 3, 2016 at 6:21 pm

  3. There is a bug in the library that prevents the callback from working reliably. Until this is fixed the ESPDuino library is a better choice. There is a version for an arduino connected to the ESP which includes MQTT capabilities.

    Sean Methot

    May 6, 2016 at 6:18 am

    • Thanks Sean for leaving your valuable feedback, i will look into ESPDuino as well.

      Regards,
      Sony

      Sony Arouje

      May 6, 2016 at 10:44 am

    • hi sean,I worry to use in last few days but required some other library which has the same working as wifiESP.I wanna use esp8266 only as wifi and Arduino Uno as the control unit which is compatible with PubSubClient.

      Md Shadab Abedin

      May 6, 2016 at 3:12 pm

      • hi Md Shadab Abedin
        Can you help me if you complete this project?
        Because I could not find a way to contact the ESp8266 through arduino using the MQTT .

        souma

        May 11, 2017 at 2:21 am

      • I am not sure what’s the issue at your end. It’s always better to post your question in Arduino forum.

        Sony Arouje

        May 11, 2017 at 10:23 am

  4. hello , i have a error on serial monitor 😦

    [WiFiEsp] Warning: Unsupported firmware
    Attempting to connect to WPA SSID: Mywifi

    but i flashed my es8266. when i wrote AT+GMR it gives : 0018000902

    what can i do

    Oguz Zuoo

    June 6, 2016 at 7:02 pm

    • I am not running any program in ESP, all the program in the post running in my Arduino Uno.

      Sony Arouje

      June 6, 2016 at 7:35 pm

  5. Hello! I am using a ESP8266-01 to enable wifi on my Arduino Uno. The ESP is connected wia the serial port on the Uno and i am using SoftSerial for debugging (via Arduino USB2Serial). The ESP-01 is powered from a separate power source.

    I manage to connect to my AP, but not to my MQTT broker (mosquitto on a raspberry pi). I get the following error in mosquitto “Socket error on client (null), disconnecting”.

    I have found one strange thing:
    In the mosquitto-logs my Uno/ESP-01 have IP: 10.0.1.16 (which is also the IP that is shown when checking all connected clients to my AP). However, when i call the function WiFi.localIP() in my Arduino sketch, it says that my IP is “10.0.1.116”. I suspect this is the reason why i cannot connect to mosquitto. I haven’t found a way to get around it though…

    Any ideas on how to solve this? Where do you think the problem lies? In WiFiesp, or pubsubclient?

    Thankful for any help!

    jon-erik@botas.se

    June 7, 2016 at 4:39 am

    • Not sure how is your code looks. As you can see in my Arduino sketch the below line

      client.subscribe(“presence”);

      will subscribe to a topic called ‘presence’ and message published to that topic will be pushed to all the Arduino’s subscribed to that topic.

      Sony Arouje

      July 5, 2016 at 10:05 am

  6. Open
    Cannot connect to MQTT-server (problem due to not showing correct local IP?) #49
    @jontebotas
    jontebotas opened this issue about 16 hours ago • edited about 16 hours ago
    Hi! I am using a ESP8266-01 to enable wifi for my Arduino Uno. The ESP-01 is connected via the RX/TX on the Uno, and i am using SoftSerial for debugging (via an Arduino USB2Serial). The ESP-01 is powered from a separate power source.

    I manage to connect to my AP (wifi), but not to my MQTT broker (mosquitto on a raspberry pi). I get the following error in mosquitto:

    “Socket error on client (null), disconnecting”
    In the serial monitor, i get that the MQTT-connection fails (RC: -2)

    The essential parts of my code:
    Declarations etc:

    #include
    #include “SoftwareSerial.h”
    #include

    WiFiEspClient espClient;
    PubSubClient client(espClient);

    char* ssid = “XXXX”;
    char* password = “XXXXXX”;
    int status = WL_IDLE_STATUS; // the Wifi radio’s status

    const char* mqtt_server = “server”;
    const char* mqtt_username = “user”;
    const char* mqtt_password = “password”;
    const char* mqtt_client_name = “cliendID”;
    My setup-loop (i’m using a macro to enable/disable serial.println for debugging)

    void setup() {

    soft.begin(9600); // SoftSerial for debugging
    Serial.begin(115200); //ESP8266-01

    delay(1000);
    WiFi.init(&Serial);

    delay(1000);

    // check for the presence of the shield
    if (WiFi.status() == WL_NO_SHIELD) {
    DEBUG_PRINTLNT(“WiFi shield not present”);
    // don’t continue
    while (true);
    }
    delay(100);

    while ( status != WL_CONNECTED) {
    DEBUG_PRINT(“Attempting to connect to WPA SSID: “);
    DEBUG_PRINT(ssid);
    DEBUG_PRINTLNT(“.”);
    status = WiFi.begin(ssid, password);
    delay(10000);
    DEBUG_PRINT(“SSID: “);
    DEBUG_PRINTLNT(WiFi.SSID());
    DEBUG_PRINT(“Wifi.status: “);
    DEBUG_PRINTLNT(status);
    DEBUG_PRINT(“IP: “);
    DEBUG_PRINTLNT(WiFi.localIP());
    DEBUG_PRINT(“Firmware version: “);
    DEBUG_PRINTLNT(WiFi.firmwareVersion());
    }

    //CONNECT TO MQTT BROKER
    client.setServer(mqtt_server, 1883);
    client.setCallback(callback);

    while (!client.connected()) {
    reconnect();
    }
    client.loop();
    }
    The reconnect() function:

    void reconnect() {
    while (!client.connected()) {
    soft.println(F(“Attempting MQTT connection…”));
    // Attempt to connect
    if (client.connect(mqtt_client_name, mqtt_username, mqtt_password,mqtt_topic_arduino_status,0,true,”offline”)) {
    mqttSubscribe(mqtt_topic_r1_status);
    mqttSubscribe(mqtt_topic_r2_status);
    } else {
    soft.print(F(“Failed, rc=”)); //using the softserial for debugging…
    soft.print(client.state());
    soft.println(F(“, will try again in 5 seconds.”));
    // Wait 5 seconds before retrying
    delay(5000);
    }
    }
    }
    I have found one strange thing:
    In the mosquitto-logs my Uno/ESP-01 have the IP: 10.0.1.16 (which is also the IP that is shown when checking the connected clients in my AP). However, when i call the function WiFi.localIP() in my Arduino sketch, it says that my local IP is “10.0.1.116”. Can this be the reason to why my MQTT-connection fails? I haven’t found a way to get around it though…

    Any ideas on how to solve this?

    Thankful for any help!
    Comment on issue
    Sign in to comment
    or sign up to join this conversation on GitHub
    Desktop version

    Jonte Botås

    June 7, 2016 at 9:10 pm

    • are you able to access any other weburl from your Arduino? Try assigning a static ip to arduino in your Router and see whether the ip is changing.

      Sony Arouje

      June 8, 2016 at 10:16 am

      • I have now tried to set a static ip in my router. When running LanScan i see that the ESP is connected to the router with the static IP (10.0.1.76), but in my serial monitor wifi.localIP() still returns a different IP (10.0.1.254). This IP is even more weird since my dhcp range is 10.0.1.2->10.0.1.200…

        Will try to find a suitable web url to connect to as well.

        Btw, sorry for the nonsense text in the beginning and end of my last post – posted my problem in the EspWifi-area on github as well and copied the text to the comment on your blog via my cell phone and didnt notice…

        Jonte Botås

        June 9, 2016 at 1:56 am

      • I now tested to bypass the Arduino and use AT commands in the serial monitor to communicate with the ESP-01. When connecting to my AP via AT+CWJAP=”….”,”…”, I do get the correct IP (my static IP). This tells me that something is wrong with EspWifi or my sketch.

        Jonte Botås

        June 9, 2016 at 2:12 am

      • WifiEsp I mean

        Jonte Botås

        June 9, 2016 at 2:12 am

  7. Please post this in Arduino forum, it’s always better to resolve these kinds of issues in a forum. I am also a member of Arduino forum. Please post your schematic as well.

    Sony Arouje

    June 13, 2016 at 3:37 pm

    • I have posted it in the WifiEsp forum. However, I have changed my setup so that my ESP-01 communicates with my UNO via I2C instead. And the ESP-01 is programmed using the ESP8266Wifi library and pubsubclient instead – which works better.

      Jonte Botås

      June 15, 2016 at 2:23 pm

  8. Hi! I want to do sockets mqtt with a Raspberry an Arduino Uno with ESP8266, In Rasp I connect to (127.0.0.1), and in Ardu to (192.168.1.135 wich is fixed in RaspB). If I publish one “topic” in Arduino, I receive it in the Rasp (with subscribe), but if I want to publish in Raspb, i can`t subscribe with Ardu, In my Serialmonitor not received any message that I publish with the rasp.
    It’s possible that I needs to use a logical conversor? Because I can send (publish), but not receive (subscribe) Thanks!!

    Oscar

    June 18, 2016 at 2:11 pm

  9. Hi! I want to do sockets mqtt with a Raspberry an Arduino Uno with ESP8266, In Rasp I connect to (127.0.0.1), and in Ardu to (192.168.1.135 wich is fixed in RaspB). If I publish one “topic” in Arduino, I receive it in the Rasp (with subscribe), but if I want to publish in Raspb, i can`t subscribe with Ardu, In my Serialmonitor not received any message that I publish with the rasp.
    It’s possible that I needs to use a logical conversor? Because I can send (publish), but not receive (subscribe) Thanks!!

    Oscar Forradellas Conte

    June 18, 2016 at 2:12 pm

    • Hi,
      I cant say anything without seeing a schematic of your esp connection to Arduino.

      It’s always better to post your question in Arduino forum, so that any one else can also answer it.

      Sony Arouje

      June 18, 2016 at 2:39 pm

      • My connections are this:
        ESP8266 —– UNO
        UTXD —– pin0 (RX)
        GND —– GND
        CH_PD —– pin 4
        URXD —– pin 1 (TX)
        Vcc —– —– —– external 3.3V
        RST —– —– —– none
        GPIO —– —– —– none
        GPIO2 —– —– —– none

        I have publish the message also in the Arduino forum, thanks!

        Oscar Forradellas Conte

        June 18, 2016 at 8:17 pm

      • Right now, I realize that when the raspb send the publish(topic), the blue led of esp8266 blink. This may be an other reason to think that I needs a conversor logic 5v/3.3v. What do you think?

        Oscar Forradellas Conte

        June 18, 2016 at 8:54 pm

      • yes you need a level shifter in TXD line of ESP, you can use two resistor as level shifter. ESP operates in 3.3v and Arduino in 5v.

        Sony Arouje

        June 30, 2016 at 11:21 am

  10. I am very new to this stuff. So i dont know much about coding. I have uploaded the coded in my arduino and copy paste the code for SERVER in a notepad with .js extension as well as the code for client in seperate notepad file with .js extension. I have also installed mongodb. I open the mongodb instance through command prompt firstly mongod and then mongo. Then in new command prompt i open my server code by ‘node server.js’ command and it gives the message ‘mosca is up’. Similarly i open new command prompt and open the ‘node client.js’ but it said nothing…and in the serial monitor its constantly saying trying to connect to client. Can you please help me? can you tell what am i doing wrong?

    Mary

    June 30, 2016 at 12:38 am

    • I am not sure what’s the issue here. I might need to see the sketch you have uploaded to Arduino. Also you can post your issue to Arduino forum, multiple eyes are better than one.

      Sony Arouje

      June 30, 2016 at 11:17 am

      • I have uploaded the same code as above in my arduino. The code you write for the arduino part. I guess the error is in the client side. Can you tell what does that mqtt ip and client id refer too? I have already posted the issue in stackoverflow but no reply from there.

        Mary

        June 30, 2016 at 11:46 pm

      • Mary, you should understand a code before copying and executing it. That’s the ip address of the MQTT server, in this case it’s the IP Address of the machine where MQTT server is running in my intranet.

        Sony Arouje

        July 1, 2016 at 7:46 am

      • In the code i have given my ip address but still its being unable to connect. I am new to all this and learning this mqtt communication that’s why i asked to confirm that what does that ip address mean. And my second question was about that client id nodeapp..is it any random name?

        Mary

        July 2, 2016 at 12:15 am

  11. Good job! Thanks for sharing!

    juanstillerjuanstiller

    July 3, 2016 at 12:16 am

    • thanks for leaving your comments.

      Sony Arouje

      July 3, 2016 at 4:18 pm

      • Sir can i use this library without using the wifi shield of ardino mega

        AMIT PRIYE

        July 15, 2016 at 2:57 pm

      • I havent used any Shield, only connected ESP to my Uno.

        Sony Arouje

        July 15, 2016 at 3:36 pm

      • Please send me the esp8266 library which compatible to mqtt pubsubclient library .i am not using the wifi shield so send me esp8266 library compatible with that

        AMIT PRIYE

        July 15, 2016 at 3:04 pm

      • I am not sure whether you read my post completely, I did mentioned the library i used and link to that library.

        Mentioning again: https://github.com/bportaluri/WiFiEsp

        Sony Arouje

        July 15, 2016 at 3:35 pm

      • Frequent connection lost with server and while connected not able to subscribe messages comes from the server. If fixed this then metion the steps what i need to change or send me link library in which this issue is fixed.
        Thanks for the reply

        Anonymous

        July 21, 2016 at 1:49 pm

      • Unable to subscribe message .frequent connection lost with sever.please provide bug free library

        Anonymous

        July 21, 2016 at 3:22 pm

      • Go back to Github and check with the author of the library. I am just using the library just like you did.

        Sony Arouje

        July 21, 2016 at 4:39 pm

  12. hi i’am working on smart office project so ,we know that we the employees swipe there rfid card and those data (in and out time with employee name and other details gets stored in data base now we have used nodemcu where whenver a employee swipes the scanner device of hi/her cubical the power goes on and when he/she swipes out the power goess off ,thirdly we have installed mqtt and configured nw i want to connect the data base with mqtt and upon dettecing details the data is sent to subscriber ( that is controller ) and upon verification the power is switched on and off …so how i can do it i mean how to connect the database and mqtt part for the rest process

    YUVRAJ

    August 31, 2016 at 12:05 pm

  13. Hallo Sony

    I had a few Wemos D1 minis laying around and wondered if they could do this job too.

    They have built-in USB connection an get power through this USB connection.

    The rest is hooked-up according your indications.
    I ran your sketch on a Arduino Mega. Just used soft serial as you did. So no changes in the sketch.

    I did not manage to initialise the ESP module. A few TIME-OUT message and at the and message about no ESP module.

    Changing to the MEGA serial1 ports made no difference.

    Do you have any suggestions?

    Ellard Postma

    Ellard Postma

    October 29, 2016 at 8:19 pm

  14. Hi @Sony Arouje, I have a trouble in your tutorial that is the code in Arduino Sketch part will be pass to Arduino chip or ESP8266 Chip? I think that everything of source code should be put in main board of Arduino to control ESP8266 card and other external devices.

    Toan

    November 14, 2016 at 1:14 pm

  15. Hi,
    I have copied your example but i am not able to subscribe to a topic. I am able to get publish messages from Arduino but i am not getting subscribed message in arduino.
    I have to get temperature data from Arduino device and publish so i am able to publish message with temperature data within 5 seconds delay. i also have to receive data from other device to Arduino for controlling Temperature sensor which is Raspberry Pi. i am also receiving published data from Raspberry pi and Arduino client on web and database using Mosquitto broker.
    when Raspberry pi publish message i am able to receive on web as well as in database but i am not able to receive that data in Arduino as subscribed message.
    I have copied your code.
    can you please let me know what problem may be? if required i will post my code

    PK

    November 14, 2016 at 5:39 pm

    • I cant figure out the issue without knowing your setup and source code.

      Sony Arouje

      November 16, 2016 at 10:06 pm

      • Hi, Here is the code

        #include “SPI.h”
        #include “WiFiEsp.h”
        #include
        #include “SoftwareSerial.h”
        #include
        #include

        float temp=0;
        int tempPin = 0;
        int isClientConnected = 0;

        char data[80];
        //char ssid[] = “SSID”; // your network SSID (name)
        //char pass[] = “PASSWORD”; // your network password

        int status = WL_IDLE_STATUS; // the Wifi radio’s status
        char deviceName = “ArduinoClient1”;

        IPAddress server(xxx,xxx,xxx,xxx); //MQTT server IP
        IPAddress ip(192,168,43,200);

        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++) {
        Serial.print((char)payload[i]);
        }
        Serial.println("-");
        }

        // Emulate Serial1 on pins 6/7 if not present
        WiFiEspClient espClient;
        PubSubClient client(espClient);

        SoftwareSerial Serial1(6,7); // RX, TX

        void setup()
        {
        Serial.begin(9600);
        Serial1.begin(9600);
        WiFi.init(&Serial1);
        WiFi.config(ip);
        if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        while (true);
        }

        while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);
        Serial.print("WiFi Status : ");
        Serial.println(status);
        }

        //connect to MQTT server
        client.setServer(server, 1883);
        client.setCallback(callback);
        isClientConnected = client.connect(deviceName);
        Serial.println("+++++++");
        Serial.print("isClientConnected : ");
        Serial.println(isClientConnected);
        Serial.print("client.state() : ");
        Serial.println(client.state());

        if (isClientConnected) {
        Serial.println("Connected…..");
        client.publish("status","Welcome to ISG");
        client.subscribe("isg/demoPublish/rpi/ardTempWarn"); // Not able to recieve for this subscribed topic on Arduino Only if i print it returns 1
        //client.subscribe("isg/demoPublish/#");
        }
        }

        void loop() {
        temp = (5.0 * analogRead(tempPin) * 100.0) / 1024;
        Serial.print(" temp : " );
        Serial.println(temp);
        Serial.print("client.connected() :");
        Serial.println(client.connected());
        if (!client.connected()) {
        reconnect();
        }
        client.publish("isg/demoPublish/ard1/tempLM35", String(temp).c_str()); // able to receive data at other clients like RPI,Web using Mosquitto broker
        client.loop();
        delay(5000);
        }

        void reconnect() {
        Serial.println("Device is trying to connect to server ");
        while (!client.connected()) {
        if (client.connect(deviceName)) {
        } else {
        delay(5000);
        }
        }
        }

        PK

        November 17, 2016 at 2:02 am

      • included files are WiFiEsp.h, WiFiEspClient.h, SoftwareSerial.h,PubSubClient.h,WiFiEspUdp.h
        I had added SPI.h but i have removed now

        PK

        November 17, 2016 at 2:11 am

  16. Hello
    My ESP is initialized at 1.0.1
    But while attempting to connect to mqtt server, it gives a time out msg followed by rc=-1 code.
    Here is the output. I tried changing the baud rate of ESP from 115200 to 9600. I am having a 12E module ESP.
    Attempting MQTT connection…[WiFiEsp] Connecting to 192.168.0.101
    [WiFiEsp] TIMEOUT: 4
    [WiFiEsp] Disconnecting 3
    failed, rc=-1 try again in 5 seconds

    Karan Makharia

    November 18, 2016 at 2:50 am

  17. Can any one please help me ??

    PK

    November 22, 2016 at 8:25 pm

  18. Sony Arouje Hello from Turkey
    Thanks for this article, really thanks.

    Mehmet Akif Özdemir

    December 12, 2016 at 2:59 am

  19. Hello Sony,

    I have implemented MQTT on Adafruit Huzzah, but planning to change to ESP 01. I have tried your code but there is some problem initializing the ESP module. I have used 3.3v from the Arduino and did not use any kind of level shifters to the TX pin. Will that be a problem? Please let me know regarding the possible issue. Thank you in advance.

    adi619

    January 10, 2017 at 12:20 am

  20. This is awesome – your example saved me tons of time. Thank you.

    I already have Mosquitto and Redis running on an RPi3 (I cache several hundred points of sensor data in Redis so that the historical data can be displayed very quickly on my IOT dashboard). The Pi also hosts a web server where I publish my sensor data live to Highcharts (plus the cached chart preload data). Here I’m using the Paho MQTT Client which provides a websocket connection to the MTT broker. The current sensor deployment is managed by an Arduino Mega with an ethernet shield. This device is already publishing the sensor data to the MQTT broker on the Pi. I thought I might try using an ESP8266 to replace the shield.

    Using your post as a guide, I was able to subscribe to my message traffic and see my sensor data in about 5 minutes. Its surprising to me, but it seems not many people are integrating these particular technologies. So cool, thanks again.

    For what its worth, I am experiencing the same connectivity issues others have reported. I see recent activity on GitHub for WiFiEsp though so I’m sure this will improve. In the meantime, I may check out ESPDuino as was also suggested. Have you tried this library yet?

    Rob

    January 13, 2017 at 9:14 am

  21. I made a mistake. I already have an Arduino Mega sending sensor data to a MQTT broker running on an RPi3. This client’s name is already “arduinoClient”. To avoid conflicts with MQTT, I changed it to “arduinoUnoClient”. My MQTT connection is now stable, but many messaging are getting lost. I will keep tweaking 😉

    if (client.connect(“arduinoUnoClient”)) {}

    Rob

    January 13, 2017 at 9:47 am

  22. Hi Sony
    Great article – Many thanks!
    I am having difficulty receiving messages – I wondered if you could help?

    I have an ESP (with 3.3v supply & level conversions) & Arduino Mega
    My MQTT broker is Mosquitto on RPi 3

    Arduino code:
    #include
    #include
    #include
    #include

    IPAddress server(192,168,1,xxx); //RPi address
    char ssid[] = “xxxxxxxxx”; // your network SSID (name)
    char pass[] = “xxxxxxxxxx”; // your network password
    int status = WL_IDLE_STATUS; // the Wifi radio’s status

    // Initialize the Ethernet client object
    WiFiEspClient espClient;

    PubSubClient client(espClient);

    //SoftwareSerial soft(2,3); // RX, TX //not used
    void setup() {
    // initialize serial for debugging
    Serial.begin(115200);
    // initialize serial for ESP module
    Serial1.begin(115200);
    // initialize ESP module
    WiFi.init(&Serial1);

    // check for the presence of the shield
    if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println(“WiFi shield not present”);
    // don’t continue
    while (true);
    }

    // attempt to connect to WiFi network
    while ( status != WL_CONNECTED) {
    Serial.print(“Attempting to connect to WPA SSID: “);
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
    }

    // you’re connected now, so print out the data
    Serial.println(“You’re connected to the network”);

    //connect to MQTT server
    client.setServer(server, 1883);
    client.setCallback(callback);
    }

    //print any message received for subscribed topic
    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')
    Serial.println("Off");
    if (receivedChar == '1')
    Serial.println("On");

    }
    Serial.println();
    }

    void loop() {
    // put your main code here, to run repeatedly:
    if (!client.connected()) {
    reconnect();
    }
    client.loop();
    }

    void reconnect() {
    // Loop until we're reconnected
    while (!client.connected()) {
    Serial.print("Attempting MQTT connection…");
    // Attempt to connect, just a name to identify the client
    if (client.connect("AMega","xxxxxx","xxxxxxxxxxx")) {
    Serial.println("connected");
    // Once connected, publish an announcement…
    // client.publish("command","Hello World");
    // … and resubscribe
    client.subscribe("switch",0);

    } else {
    Serial.print("failed, rc=");
    Serial.print(client.state());
    Serial.println(" try again in 5 seconds");
    // Wait 5 seconds before retrying
    delay(5000);
    }
    }
    }

    This connects to WiFi fine & to an MQTT broker running on a raspberry Pi(3)
    (Mosquitto 1.4.10 as part of emonpi software from OpenEnergyMonitor)

    Serial Monitor:

    [WiFiEsp] Initializing ESP module
    [WiFiEsp] Initilization successful – 1.3.0
    Attempting to connect to WPA SSID: xxxxxxxxxx
    [WiFiEsp] Connected to xxxxxxxxxxxx
    You're connected to the network
    Attempting MQTT connection…[WiFiEsp] Connecting to xxxxxx
    connected
    [WiFiEsp] Disconnecting 3
    Attempting MQTT connection…[WiFiEsp] Connecting to xxxxxx
    connected
    (It disconnects every 30 seconds or so and reconnects)

    It posts to the Pi (If // client.publish("command","Hello World"); is uncommented) but does not receive subscribed messages. – "Message arrived" is never printed
    I also have an MQTT client on my android phone. This communicates fine with the RPi
    Again the Arduino can publish to my phone but cannot receive with subscribe

    I am not sure where to go next – everything I look at seems to be working but it won't receive subscribed topics?

    UPDATE:

    client.subscribe("switch",0) returns "true" so maybe the problem is with "callback"?
    No messages are printed out, I have tried many different formats
    I am basically wish to use this for control The messages will generally be short!

    Any help would be appreciated

    Richard

    Richard Hatfield

    January 25, 2017 at 3:58 am

  23. Hi Sony,
    I just want to say thank you! Your example is simple at to the point. I was able to get things running without dividers and using the 3.3 V from the Arduino. I recently read that other than the power the ESP is capable of managing 5v I/O, so I am just checking it out. One point to note from my setup the RX and TX are in reverse order for Pin 2 and pin 3.
    Thanks again!
    Julio C.

    Julio Montoya

    January 30, 2017 at 9:49 am

    • Thanks for leaving your comments. Might work without voltage dividers, but I always try to provide the right voltage as per spec. Because these systems I design should work 24/7.

      Sony Arouje

      February 5, 2017 at 6:14 pm

  24. Hy Help me
    I use 4duino (4duino.com) is Board Arduino with esp8266
    But scketch do not work , ” TIME OUT”. comunication

    HELP ME

    Andrea Lombardi

    February 8, 2017 at 4:57 am

    • Check your connections again. I am not sure how to help you with the limited info you posted. It’s always good to post it in Arduino forum, you will get help from a lot of members. Make sure you post enough details not like need help with Timeout, no one could help you.

      Sony Arouje

      February 8, 2017 at 10:03 am

  25. Hello I made All CONNECTIONS as described to you
    The Problem + What I go to timeot

    [WiFiEsp] >>> >>> TIMEOUT
    [WiFiEsp] No tag found
    ********************************************** Check SSID> PASSED

    Andrea Lombardi

    February 8, 2017 at 1:20 pm

  26. hello I’m making great progress thanks to you.
    you are the best
    Now I connect to the router can not reach external source where I’m trying MQTT
    He tells me the following error:

    Attempting MQTT connection … [WiFiEsp] Connecting to 52.28.77.89
    [WiFiEsp] >>> >>> TIMEOUT

    HELP
    SOPHIA

    Andrea Lombardi

    February 8, 2017 at 2:38 pm

    • Are you able to ping that ip using ping command?

      Sony Arouje

      February 9, 2017 at 9:19 am

      • Hy Sony
        I was able to connect to the server, any message arrives but often goes rc error
        Which can be error?

        Sophia Kiss

        Andrea Lombardi

        February 10, 2017 at 2:34 am

  27. Hi…. Will you suggest me a suitable method to enable data transfer between two esp 8266 using arduino and the required libraries?

    sam

    February 17, 2017 at 11:17 pm

  28. Hello
    I have 2 problems, I have to continually send out a date Otherwise AFTER 15 Seconds disconnects.
    InOLTRE not understand come subscrite works.
    I Created on my node a topic that the data sent EVERY 5 seconds.
    Arduino I used subscrite but I can not SEE anything.

    Andrea Lombardi

    March 6, 2017 at 4:37 am

  29. 1 Problem
    I have to enter a polling otherwise I will disconnect all also wifee
    2) problem
    It does not work subscrite

    andrea Lombardi

    March 6, 2017 at 9:05 pm

  30. 1 Problem
    disconnected between keepalive time
    2 problem
    It does not work subscrite

    zhoufusong

    April 13, 2017 at 9:15 am

  31. Hello, I’m using your tutorial to use my ESP8266-01 as a WiFi module for my Arduino Uno to send some data using MQTT. But my problem now is that I want to make this MQTT connection secure using SSL. But all the discussions and code I found were using the ESP directly or using a WiFi board for Arduino.

    Do you know any methods to make this connection secure using the ESP as a module?

    PEDRO RIBEIRO

    September 8, 2017 at 4:10 am

  32. i am making a project in home automation using wifi module esp-01 and arduino uno but how can i send data to arduino from my android app to the board and control the leds and does i need a web server or shoukd i use mqtt m confuse a bit pls help

    Harshil Bhagat

    February 22, 2018 at 11:38 pm

    • I created a webserver and call the service to send any commands to MQTT client. I don’t know whether you can send MQTT commands directly from Android. For my requirement I required a web service.

      Sony Arouje

      February 23, 2018 at 8:13 am

  33. hi, Sony
    So great your artical
    Could you please Notice the firmware version of your ESP8266. In mine, it was 1.0.0.0, I dont know wether it would work.
    Thanks a lot !

    mike ju

    March 27, 2018 at 7:25 pm

  34. Hi Sony I am using Arduino UNO and ESP8266 as my client , Raspberry Pi3 and Mosquitto MQTT as mqtt srever and a D-Link wifi Router (Which is not connected to Internet but working as an wifi AP).
    I have used the above Sketch.
    Arduino UNO Esp8266 is connecting properly.But connection to the MQTT server failed.
    On serial monitor this message is coming “FAILED RC=2”.
    Please guide me how to resolve the issue.

    Debashis Gayen

    March 31, 2018 at 8:54 pm

    • Hi, not sure about the reason for the connection issues. I am not doing much with esp these days.

      Sony Arouje

      April 2, 2018 at 1:25 pm

    • Hi,
      I have the same issue.
      Did you solve the problem?

      Leo

      May 26, 2018 at 12:18 pm

  35. Hi , Sony
    I am using Arduino UNO and ESP8266 as my client and follow your guide.
    But it cant connect to MQTT server and i get a call back below.
    failed, rc = -2 try again in 5 seconds.
    Do you know what the problem?

    leo

    May 24, 2018 at 3:29 pm

    • I dont know what could be the issue. Its been a long time I touched ESP.

      Sony Arouje

      May 24, 2018 at 3:31 pm

  36. Hi Sony,

    i have a project Esp8266 & temperatire sensor for my graduate,
    i cannot connect my server broker with mqtt websocket, if you used PubSubClint library for mqtt://localhost:”port-mqtt”, how about mqtt websocket using url ws://localhost:”port-ws”..

    how i can connect arduino Esp8266 to my server broker with mqtt websocket?? How to solved that Sir?

    i’m sorry about my bad english,
    Thanks.

    • Hi Alvy, I haven’t used ws instead of mqtt. Sorry i might not clarify your query. May be you can post the query in arduino forum.

      Sony Arouje

      July 17, 2018 at 8:28 am

  37. Hi Sony,

    I am new to MQTT implementation. Can you please explain, how the mqtt puplish/subsribe request is handle in your implementation.

    Why client code is required? if ESP8266 is sending the request to server directly?

    When ESP8266 publish something, how is data flows in your example? How the request is handled by the client and server. (Server uses Mosca and Client uses MQTT module.)

    If I want to implement a local MQTT server, How I can proceed?

    Maheshwar G Mangat

    July 31, 2019 at 2:56 am

    • Here client node code will send data via presence channel, so here its a publisher.
      Same time the node client app also a subscriber of command channel

      Arduino code is a subscriber of Presence channel and same time publisher of command channel.

      So any time client node send any message via presence channel arduino will get notified. Same way if arduino will send any message via command channel node client will get notified.

      Imagine here node client app can be your webservice which will get called via a mobile app, The mobile app says switch off a device, the webservice can publish the same to the respective arduino via some channel and arduino can switch off the device for you.

      Sony Arouje

      August 5, 2019 at 8:51 am

      • Thanks a lot sir ….I will try to implement the same and if any difficulty, get back to you.

        maheshwar mangat

        August 6, 2019 at 12:26 pm

  38. Dear friend,
    I have problem to connect with mqtt broker. I use hive mqtt broker. Please check my server
    .

    Anonymous

    August 7, 2019 at 9:15 pm

  39. Hey Sony,
    thank you sooooo much for sharing your concept.
    You realy helped me out with that compination of two libraries.

    But one thing to say:
    If you guys are using the ESP8266 you should change the Baudrate to 9600. Because my Arduino can’t handle such a high rate as 115200. That caused many errors in my case. Therefore the EspDrv.cpp couldn’t get the Flags and I got the error: failed, rc=-2 what means that there’s a physical connection issue. So i changed the baudrate to 9600. If you need more information please look at this post: https://arduino.stackexchange.com/questions/36447/wifiesp-not-working-on-software-serial-working-fine-on-hardware-serial/36453#36453
    After this quick fix the concept was awsome.
    Thanks again.

    Nils Jacobsen

    April 3, 2020 at 6:58 pm


Leave a comment