I want to read a sensor value using Arduino UNO and then publish the value to an MQTT server. I have used the ESP-01 Wi-Fi module to connect to the Wi-Fi network. Everything works fine; the setup connects to the Wi-Fi network, then connects to the MQTT server and sends data for the first several sequences. However, after sending the first several data, it constantly automatically disconnects from the MQTT server and tries to reconnect to the server. Then, it connects to the MQTT server and sends some data. Again, after sending some data, it automatically disconnects from the MQTT server and tries to reconnect to the server. And it is continuously happening; I mean disconnecting and reconnecting.
For simplicity, I am giving a basic structure of the example code I used to publish the "hello world" message. Still, the issue is the same: continuous disconnecting and reconnecting to the MQTT server.
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <PubSubClient.h>
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(6, 7); // RX, TX
char ssid[] = "ABCDEFGHI"; // network SSID (name)
char pass[] = "123456789"; // network password
const char* mqtt_server = "test.mosquitto.org"; // MQTT broker
WiFiEspClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
Serial.begin(115200);
ESPserial.begin(115200);
// initialize ESP module
WiFi.init(&ESPserial);
// attempt to connect to WiFi network
while (WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
delay(5000);
}
Serial.print("You're connected to the network. IP Address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until reconnection
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ArduinoClient")) {
Serial.println("connected");
client.publish("outTopic", "hello world");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Publish a message every 10 seconds
static unsigned long lastMsg = 0;
unsigned long now = millis();
if (now - lastMsg > 10000) {
lastMsg = now;
char msg[50];
snprintf(msg, 50, "hello world #%ld", now / 1000);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("outTopic", msg);
}
}
I have a stable Wi-Fi network connection, so it is impossible to have a network connectivity issue. While reading the forum, some said to use a unique client ID.
if (client.connect("ArduinoClient"))
I have tried using a unique client ID instead of "ArduinoClient", but the problem persists.
Since the setup must be done with the Arduino UNO, this is the only microcontroller board to use. Therefore, any suggestions from the experts would be greatly appreciated. Thank you for your time.