Mqtt Connection

Hello I am new to Arduino IDE and this is my first post. I am having trouble with connecting my Arduino Mega2560 with W5100 ethernet shield to MQTT. I can connect to my local network over ethernet and obtain an IP address, so no issues there. I also can connect to another MQTT broker via adafruit and publish/subscribe to a topic so it does not seem to be a hardware issue. The only problem I have been having is with my own MQTT Broker hosted on another computer, my arduino mega wont publish or subscribe to any messages, the MQTT Broker has other devices on other networks publishing/subscribing to it, so the broker works. Maybe its an issue with the code (code below)???? All the IP addresses and authentication are default and not what I will be using. To read any messages I publish I have a mqtt node on node-red on my local computer (the one not hosting the mqtt).

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(172, 16, 0, 100);
IPAddress server(172, 16, 0, 2);

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
}

EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);

void setup()
{
  Ethernet.begin(mac, ip);
  // Note - the default maximum packet size is 128 bytes. If the
  // combined length of clientId, username and password exceed this use the
  // following to increase the buffer size:
  client.setBufferSize(255);
  
  if (client.connect("arduino", "test", "test123")) {
    client.publish("outTopic","hello world");
    client.subscribe("inTopic");
  }
}

void loop()
{
  client.loop();
}

Possible duplicate client id causing an immediate disconnect. If you are running mosquitto on Linux look at the connection logs.
In place of "arduino" as the client id try some random id such as "xyz123999".

ok thanks I will give that a try

Still nothing

I even tried to throw a delay on the ethernet.begin(mac, IP) incase it was not given enough time to initialize.

Both publish and subscribe return bool. Does the library report that the calls work?

You might try another library, like ArduinoMqttClient, currently at version 0.1.18

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.