Pubsubclient: MQTT USING ARDUINO NANO AND ESP8266-WifiEsp and PubSubClient library.

Created on 15 May 2017  Â·  17Comments  Â·  Source: knolleary/pubsubclient

Hi Nick,
I am using a setup consisting of Arduino Nano and ESP8266.I tried sample codes using WifiEsp and PubSubClient libraries.But the only response is rc=-2.But the can successfully connect esp to Internet.Please give me solution to this issue ASAP.I have also attached the sample code I worked on.

#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
//#include "SoftwareSerial.h"
#include <PubSubClient.h>


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 Serial1(2,3); // RX, TX   //ESP8266 RX,TX connected to these pins
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("mqttserver.com", 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("NANO","xxxxxx","xxxxxxxxxxx")) {
Serial.println("connected");
// Once connected, publish an announcement...
// client.publish("outpic","Hello World");
// ... and resubscribe
client.subscribe("intopic",0);

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

Thanks,
Sundar

Most helpful comment

I had met with a same question, then I found it is the ESP8266's board's baud rate issue.
Change to 9600 baud. It is probably at 115200 right now.
set up the baud rate first.
Set the init command to esp8266 first

AT+UART_DEF=9600,8,1,0,0

Then the communication is ok and every thing will be ok.
you can also refer to this
https://arduino.stackexchange.com/questions/36447/wifiesp-not-working-on-software-serial-working-fine-on-hardware-serial

All 17 comments

Sorry, I don't know why your code isn't working.

Sir is there a way I can contact you.I need to set up communication via MQTT.Can I ask you for a solution.For that I am in need of your contact.

Hi, you are in contact with me.

I've never tried using this library with an ESP connected to an Arduino as you have, so I don't have first-hand experience of it.

Using google, I quickly found lots of examples where other people have had issues with this pair - I'm sure you'd be able to find the same.

Once common 'fix' was to not call client.loop() so often as it overwhelms the serial connection between the arduino and esp.

Try adding a delay(1000) before the call to client.loop()

Attempting MQTT connection...[WiFiEsp] Connecting to mqtt.dioty.co
[WiFiEsp] >>> TIMEOUT >>>
failed, rc=-2 try again in 5 seconds
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] No tag found
Attempting MQTT connection...[WiFiEsp] Connecting to mqtt.dioty.co
failed, rc=-2 try again in 5 seconds
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] No tag found
Attempting MQTT connection...[WiFiEsp] Connecting to mqtt.dioty.co
failed, rc=-2 try again in 5 seconds
[WiFiEsp] >>> TIMEOUT >>>

Sir,this is what I get on the terminal.I actually added a 1000ms delay before client.loop().

What aboutusing a nodeMCU Sir.Will that work error-less for an MQTT protocol.,ie both subscribing and publishing should work well.If yes I can shift from Arduino to nodeMCU.

Thanks,
Sundar

A -2 error means the underlying tcp connection failed. That's before the PubSubClient tries doing anything with the connection.

I suggest you try one of the example HTTP sketches to verify your hardware and ability to connect to the network etc. Other than that, I don;t have any other suggestions - as I said, this isn't a hardware combination I have any first-hand experience of. A google search finds others who have been more successful; you may want to see what they did.

okay Sir thanks for your help.

Sir ,
I have a request from my side.Can you spare some time to teach me MQTT somewhat in detailed manner.This can help me get a good job this month.Waiting for a positive reply from you.
Thanks,
Sundar

I would recommend you to get a NodeMCU,then install : esp8266 by ESP8266 Community (via Arduino Board Manager), open _mqtt_esp8266.ino_ from pubsubclient library examples, choose your board (NodeMCU 0.9 or NodeMCU 1.0). Everything works for me. My NodeMCU subscribes to CloudMQTT server and then publishes all data to Cayenne (My Devices) platform (like bridge...). Publishing to CloudMQTT server is via GSM module (tinyGSM library.)

Hi,
Yes ,now I am using nodeMCU only for MQTT.It works fine.I am using hiveMQ as broker.Thanks for your help.
Cheers,
Sundar

You should change ESP8266 from 115200 to 9600 via FTDI or... if you use Arduino Nano to send data using wifi.

knolleary, thanks for the tip about the delay after the call for client.loop(), i was facing problems and now everything works. Thank you very much.

Hi everyone,

@knolleary Thank you for this great library!

I have been fighting with some issues with my Arduino Mega connected to an ESP01 via a level converter(9600 baud). MQTT server is running on my Raspberry Pi. There are 3 other Arduino Megas running on the same pubsubclient library with Ethernet shield and showing no problems whatsoever, so it does seem to be ESP related.

The whole setup works perfectly when it comes to publishing messages only. Then even with the connection checks it works fine.
The issues start with calling the client.loop() indeed. At varying intervals I have had several disconnects from the server, the network, everything.

I'm using the wifiesp library (https://github.com/bportaluri/WiFiEsp), with my ESP on version 2.1.0 being the latest available as far as I know.

I have increased the RX/TX buffers to 256 from 128 in the hardwareserial.h, the ESP is running on Serial1.

My script only calls client.loop() in every second with a non-blocking techinque:

if (millis()-lastclientloop > 1000)
{
boolean clientconnected = client.loop();
if (!clientconnected)
{reconnect;}
lastclientloop = millis();
}
This gave me about 15-30 seconds between MQTT server disconnects, usually resulting in [WifiEsp] TIMEOUT: 2 error messages, which were followed by the disconnection of MQTT server and the reconnect routine being called a bit later.

After some playing around, I have increased the KEEPALIVE time in the pubsubclient.h file to 3600 seconds (my setup publishes in every 10 seconds and should receive in every 60 seconds max), and the MQTT Disconnects are now completely gone.
I still get [WifiESP] TIMEOUT: 34 in about every 10-15 minutes, but it is already much better than it was originally. MQTT messages are published-received after the ~19 seconds reconnect of the WifiESP library without any problems, no MQTT disconnect messages are generated.

If anyone has a good solution/idea for this issue, I'd be happy to hear it. If I find a solution I'll post it, and thanks everyone for all the comments so far!

You can use Raspberry Pi 3 or zero W including: wifi and wired Internet
which has libraries of free python (send data to webs and MQTT free). About
frequency rate is very good.

2018-01-07 23:15 GMT+07:00 Jagohu notifications@github.com:

Hi everyone,

@knolleary https://github.com/knolleary Thank you for this great
library!

I have been fighting with some issues with my Arduino Mega connected to an
ESP01 via a level converter(9600 baud). MQTT server is running on my
Raspberry Pi. There are 3 other Arduino Megas running on the same
pubsubclient library with Ethernet shield and showing no problems
whatsoever, so it does seem to be ESP related.

The whole setup works perfectly when it comes to publishing messages only.
Then even with the connection checks it works fine.
The issues start with calling the client.loop() indeed. At varying
intervals I have had several disconnects from the server, the network,
everything.

I'm using the wifiesp library (https://github.com/bportaluri/WiFiEsp),
with my ESP on version 2.1.0 being the latest available as far as I know.

I have increased the RX/TX buffers to 256 from 128 in the
hardwareserial.h, the ESP is running on Serial1.

My script only calls client.loop() in every second with a non-blocking
techinque:

if (millis()-lastclientloop > 1000)
{
boolean clientconnected = client.loop();
if (!clientconnected)
{reconnect;}
lastclientloop = millis();
}
This gave me about 15-30 seconds between MQTT server disconnects, usually
resulting in [WifiEsp] TIMEOUT: 2 error messages, which were followed by
the disconnection of MQTT server and the reconnect routine being called a
bit later.

After some playing around, I have increased the KEEPALIVE time in the
pubsubclient.h file to 3600 seconds (my setup publishes in every 10 seconds
and should receive in every 60 seconds max), and the MQTT Disconnects are
now completely gone.
I still get [WifiESP] TIMEOUT: 34 in about every 10-15 minutes, but it is
already much better than it was originally. MQTT messages are
published-received after the ~19 seconds reconnect of the WifiESP library
without any problems, no MQTT disconnect messages are generated.

If anyone has a good solution/idea for this issue, I'd be happy to hear
it. If I find a solution I'll post it, and thanks everyone for all the
comments so far!

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/knolleary/pubsubclient/issues/284#issuecomment-355833465,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AY6-eoO_4CJfELupZTGNRQ08OUoCMzgzks5tIO2egaJpZM4Naslk
.

Not sure if it's helpful or not, but I made an example where you handle the MQTT communication with ESP8266 and send commands over serial connection to Arduino Uno. I used a different MQTT library, but it will work PubSub too since PubSub doesn't have any problems on the ESP8266. (For people who want to use MQTT with Arduino)

Basically, in my example you upload one code to the ESP8266 and the other to the Arduino development board, link to the code:
https://github.com/Hami24/ArduinoIoT

I had met with a same question, then I found it is the ESP8266's board's baud rate issue.
Change to 9600 baud. It is probably at 115200 right now.
set up the baud rate first.
Set the init command to esp8266 first

AT+UART_DEF=9600,8,1,0,0

Then the communication is ok and every thing will be ok.
you can also refer to this
https://arduino.stackexchange.com/questions/36447/wifiesp-not-working-on-software-serial-working-fine-on-hardware-serial

How can I add this to the code? What is now the fixed code? @senion @sundarkrish

Was this page helpful?
0 / 5 - 0 ratings