I need to create a connection between arduino and python with the help of mqtt. I want to make the arduino the server and to get the data in python.
I found online a code and worked on it for my ip connection and mac address, but somehow the serial monitor ouputs that the connection is not successful. How can I debug the code to send data from arduino?
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Function prototypes
void subscribeReceive(char* topic, byte* payload, unsigned int length);
// Set your MAC address and IP address here
byte mac[] = { 0x90, 0x61, 0xAE, 0xEE, 0x10, 0x29 };
IPAddress ip(192, 168, 0, 138);
// Make sure to leave out the http and slashes!
//const char* server = "test.mosquitto.org";
const char* server = "broker.emqx.io";
// Ethernet and MQTT related objects
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);
void setup()
{
// Useful for debugging purposes
Serial.begin(9600);
// Start the ethernet connection
Ethernet.begin(mac, ip);
// Ethernet takes some time to boot!
delay(3000);
// Set the MQTT server to the server stated above ^
mqttClient.setServer(server, 1883);
// Attempt to connect to the server with the ID "myClientID"
if (mqttClient.connect("myClientID"))
{
Serial.println("Connection has been established, well done");
// Establish the subscribe event
mqttClient.setCallback(subscribeReceive);
}
else
{
Serial.println("Looks like the server connection failed...");
}
}
void loop()
{
mqttClient.loop();
// Ensure that we are subscribed to the topic "MakerIOTopic"
mqttClient.subscribe("MakerIOTopic");
// Attempt to publish a value to the topic "MakerIOTopic"
if(mqttClient.publish("MakerIOTopic", "Hello World"))
{
Serial.println("Publish message success");
}
else
{
Serial.println("Could not send message :(");
}
delay(4000);
}
void subscribeReceive(char* topic, byte* payload, unsigned int length)
{
Serial.print("Topic: ");
Serial.println(topic);
Serial.print("Message: ");
for(int i = 0; i < length; i ++)
{
Serial.print(char(payload[i]));
}
Serial.println("");
}
In python, I would need afterwards to subscribe to the connection.
What am I doing wrong in the arduino sketch?
I attach the screenshots with the ip and mac address:

