Conexión MQTT con Arduino Nano + ESP-01

Hola.

Llevo días intentando conectar un Arduino Nano a Node-Red a través de un servicio MQTT.

Para realizar la conexión WiFi del Arduino, tengo conectado un chip ESP-01s a través de un adaptador. Para ello uso la librería “WiFiEsp.h” y puedo ejecutar correctamente los ejemplos que vienen con la librería.

El problema es cuando después introduzco la conexión a MQTT. El broker MQTT lo emulo desde Node-Red a través del nodo “Mosca MQTT broker”.

Primeramente se conecta al servidor MQTT, pero a continuación se desconecta. Este es el error que sale en la consola Serial de Arduino:

[WiFiEsp] Initilization successful - 1.5.4
Attempting to connect to WPA SSID: vodafoneAA80
[WiFiEsp] Connected to vodafoneAA80
You’re connected to the network

Iniciado STA: vodafoneAA80
IP address: 192.168.0.22
Attempting to connect to MQTT broker at 192.168.0.10
[WiFiEsp] Connecting to 192.168.0.10
Connected to MQTT broker
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Data packet send error (2)
[WiFiEsp] Failed to write to socket 3
[WiFiEsp] Disconnecting 3
Attempting to connect to MQTT broker at 192.168.0.10
[WiFiEsp] Connecting to 192.168.0.10
Connection to MQTT server failed, rc=-2 trying again in 5 seconds
[WiFiEsp] Disconnecting 3
Attempting to connect to MQTT broker at 192.168.0.10
[WiFiEsp] Connecting to 192.168.0.10
Connected to MQTT broker

El código que utilizo es este:

#ifndef HAVE_HWSERIAL1
#include <SoftwareSerial.h>
SoftwareSerial Serial1(3, 2); // RX, TX
#endif

#include <WiFiEsp.h>
#include <PubSubClient.h>

int status = WL_IDLE_STATUS;
const char ssid[] = "xxx";
const char pass[] = "xxx";

int ESTADO = LOW;
int LED = 6;


//MQTT
const IPAddress mqttServerIP(192,168,0,10);
const char* deviceID = "ArduinoNano";
WiFiEspClient wifiClient;
PubSubClient MQTTclient(wifiClient);
long lastMsgTime = 0;
char msg[64];
char topic[32];
int pulseCount = 0;



void setup()
{
  
  Serial.begin(9600); 
  
  pinMode(LED, OUTPUT);	 
  digitalWrite(LED, LOW);
  pinMode(7, INPUT_PULLUP);
  
  wifiSetup();
  mqttSetup();
}

void loop()
{
  if(digitalRead(7) == LOW)
  {
    if(ESTADO == LOW){
      Serial.println("Pulsado boton - Voy a abrir");
      Abrir();  
    }else{
      Serial.println("Pulsado boton - Voy a cerrar");
      Cerrar();
    }
  }
  mqttLoop();  
  delay(100); 

}


void Abrir(){
  Serial.println(F("LED encendido!"));
  ESTADO = HIGH;
  digitalWrite(LED, HIGH); 
  publish("LED encendido!");
  delay(2000);
}
void Cerrar(){
  Serial.println(F("LED apagado!"));
  ESTADO = LOW;
  digitalWrite(LED, LOW);  
  publish("LED apagado!");
  delay(2000);
}
void Resetear(){
  Serial.println(F("LED Puzzle Reset!"));
  digitalWrite(LED, LOW);
  publish("LED puzzle reset!");
  delay(1000);
}

void wifiSetup() {
  Serial1.begin(9600);
  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
    //WiFi.config(ip);
    status = WiFi.begin(ssid, pass);
  }
   Serial.println("You're connected to the network");
   Serial.println("");
   while (WiFi.status() != WL_CONNECTED) 
   { 
     delay(100);  
     Serial.print('.'); 
   }
   Serial.println("");
   Serial.print("Iniciado STA:\t");
   Serial.println(ssid);
   Serial.print("IP address:\t");
   Serial.println(WiFi.localIP());
}


void mqttCallback(char* topic, byte* payload, unsigned int length) {

  // The message "payload" passed to this function is a byte*
  // Let's first copy its contents to the msg char[] array
  memcpy(msg, payload, length);
  // Add a NULL terminator to the message to make it a correct string
  msg[length] = '\0';

  // Debug
  Serial.print("Message received in topic [");
  Serial.print(topic);
  Serial.print("] ");
  Serial.println(msg);

  // Act upon the message received
  if(strcmp(msg, "ABRIR") == 0) {
    Abrir();
  }
  else if(strcmp(msg, "CERRAR") == 0) {
    Cerrar();
  }
  else if(strcmp(msg, "RESET") == 0) {
    Resetear();
  }
}

void mqttSetup() {
  // Define some settings for the MQTT client
  MQTTclient.setServer(mqttServerIP, 1883);
  MQTTclient.setCallback(mqttCallback);
}

void mqttLoop() {
  // Ensure there's a connection to the MQTT server
  while (!MQTTclient.connected()) {
  
    // Debug info
    Serial.print("Attempting to connect to MQTT broker at ");
    Serial.println(mqttServerIP);

    // Attempt to connect
    if (MQTTclient.connect(deviceID)) {
    
      // Debug info
      Serial.println("Connected to MQTT broker");
      
      // Once connected, publish an announcement to the ToHost/#deviceID# topic
      snprintf(topic, 32, "ToHost/%s", deviceID);
      snprintf(msg, 64, "CONNECT", deviceID);
      MQTTclient.publish(topic, msg);
      
      // Subscribe to topics meant for this device
      snprintf(topic, 32, "ToDevice/%s", deviceID);
      MQTTclient.subscribe(topic);
      
      // Subscribe to topics meant for all devices
      MQTTclient.subscribe("ToDevice/All");
    }
    else {
      // Debug info why connection could not be made
      Serial.print("Connection to MQTT server failed, rc=");
      Serial.print(MQTTclient.state());
      Serial.println(" trying again in 5 seconds");
      
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
  
  // Call the main loop to check for and publish messages
  MQTTclient.loop();
}


void publish(char* message){
  snprintf(topic, 32, "ToHost/%s", deviceID);
  MQTTclient.publish(topic, message);
}

Ya no sé si es un error en el código, en el hardware, de configuración del router… ¿Alguien puede ayudarme?

Muchas gracias.