Hello, I'm new to this forum and to this topic.
My final objective is to connect my Arduino Uno with a ESP8266 - ESP01 to a Raspberry Pi 3.
As I am new to the networking topic I thought I could make both communicate via a MQTT broker.
I found this blog that had an example to connect my ESP to a broker.
But when I do the connection it says that is connected but then it disconnects and stays on a loop connecting and disconnecting. Anyone had this kind of problem before?
If anyone wants to help, I'll but my code below:
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
//#include <WiFiEspUdp.h>
//#include <WiFiClient.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#define DEBUG true
//Connecting to the Wifi
const char* ssid = "Gandhi";
const char* pass = "newPassw0rd";
const char* mqtt_server = "iot.eclipse.org";
const char* mqtt_topic = "ArdUnoLEDStatus";
int status = WL_IDLE_STATUS;
IPAddress ip(192, 168, 115, 102);
IPAddress gateway(192, 168, 115, 1);
IPAddress subnet(255, 255, 255, 0);
WiFiEspClient espClient;
PubSubClient client(espClient);
SoftwareSerial esp8266(3,2);
const byte ledPin = 8;
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(ledPin, LOW);
//
// if (receivedChar == '1');
// digitalWrite(ledPin, HIGH);
// }
Serial.println();
}
void reconnect(){
// Loop until we're reconnected
while(!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if(client.connect("ESP8266 Client"))
{
Serial.println("connected");
client.subscribe(mqtt_topic); //Connecting to the topic
delay(3000);
Serial.println("Sending Message to Topic");
client.publish(mqtt_topic,"Arduino Test");
delay(3000);
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000); // wait for 5 seconds
}
}
Serial.println("I'm connected and heading out from the Reconnect function");
}
void setup(){
Serial.begin(9600);
esp8266.begin(9600);
WiFi.init(&esp8266);
// 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);
}
Serial.println("You're connected to WiFi now");
Serial.println("WiFi status :" + WiFi.status());
Serial.println("Setting Server");
client.setServer(mqtt_server, 1883);
Serial.println("Callback:");
client.setCallback(callback);
pinMode(ledPin, OUTPUT);
}
void loop(){
if (!client.connected())
{
reconnect();
}
client.loop();
}
Thank you.