First of all, thank you for the replies.
but possibly you want talk about a
MQTT network with RPI as broker and WIFI Arduino as MQTT client
Yes, I'm trying to do something like that. I'm following this tutorial:
https://sonyarouje.com/2016/03/15/mqtt- ... 66-esp-01/ to connect the esp8266 and the arduino to a MQTT broker. But I still have a problem, my esp8266 keeps connecting and reconnecting to the Broker. I'll but my code below if anyone is interested to help.
But my final objective isn't this, what I want to do is to make a small IoT network with the RPi and the arduino, and test some security systems and protocols. And I think that the esp8266 won't have the computational power necessary for that.
Code: Select all
#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 = "********";
const char* pass = "*******";
const char* mqtt_server = "iot.eclipse.org";
const char* mqtt_topic = "ArdUnoLED";
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
client.publish(mqtt_topic, "Arduino Test");
}
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");
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(ledPin, OUTPUT);
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
}