Hey guys,
it is the second evening I try to get a basic MQTT application running. But it just doesn't work and I really can't figure out why.
I have an Arduino Mega and an ethernet shield w5100 attached to it. I think the issue is somehow related to the Arduino itself.
I found some examples and tried to get the best out of them in order to create my own code which looks like the following. I just removed my server credentials ![]()
#include <Ethernet.h>// Ethernet.h library
#include <PubSubClient.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#define LED_PIN 12
#define DHTPIN 52 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
const char* mqttServer = "192.168.178.53";
const char* mqttUsername = "User";
const char* mqttPassword = "Password";
const char* mqttDeviceId = "Arduino";
char subTopic[] = "ledControl"; //payload[0] will control/set LED
char pubTopic[] = "ledState"; //payload[0] will have ledState value
char temperatureTopic[] = "Sensorknoten1/Temperatur/state";
char humidityTopic[] = "Sensorknoten1/Luftfeuchtigkeit/state";
String ip = "";
uint8_t mac[6] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x06};
EthernetClient ethClient;
PubSubClient client(ethClient);
long lastMsg = 0;
char msg[50];
int value = 0;
int ledState = 0;
DHT_Unified dht(DHTPIN, DHTTYPE);
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("topic: ");
Serial.print(topic);
Serial.print(" message: ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
if ((char)payload[0] == '1')
{
digitalWrite(LED_PIN, HIGH);
ledState = 1;
char payLoad[1];
itoa(ledState, payLoad, 10);
client.publish(pubTopic, payLoad);
}
else
{
digitalWrite(LED_PIN, LOW);
ledState = 0;
char payLoad[1];
itoa(ledState, payLoad, 10);
client.publish(pubTopic, payLoad);
}
}
void connect()
{
Serial.println("connecting to local MQTT broker...");
if (client.connect(mqttDeviceId, mqttUsername, mqttPassword))
{
Serial.println("connected.");
//client.subscribe(subTopic);
} else
{
Serial.print("failed, rc=");
Serial.print(client.state());
}
}
void reconnect()
{
while (!client.connected())
{
Serial.print("connecting to local MQTT broker...");
if (client.connect(mqttDeviceId, mqttUsername, mqttPassword))
{
Serial.println("connected.");
client.subscribe(subTopic);
} else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup()
{
pinMode(LED_PIN, OUTPUT);
Serial.begin(115200);
Serial.println();
Serial.println("MQTT Arduino Demo");
// setup ethernet communication using DHCP
if (Ethernet.begin(mac) == 0) {
//Serial.println(F("Unable to configure Ethernet using DHCP"));
for (;;);
}
Serial.println(F("Ethernet configured via DHCP"));
Serial.print("IP address: ");
Serial.println(Ethernet.localIP());
Serial.println();
//convert ip Array into String
ip = String (Ethernet.localIP()[0]);
ip = ip + ".";
ip = ip + String (Ethernet.localIP()[1]);
ip = ip + ".";
ip = ip + String (Ethernet.localIP()[2]);
ip = ip + ".";
ip = ip + String (Ethernet.localIP()[3]);
//Serial.println(ip);
client.setServer(mqttServer, 1883);
client.setCallback(callback);
connect();
dht.begin();
// Print temperature sensor details.
sensor_t sensor;
dht.temperature().getSensor(&sensor);
Serial.println(F("------------------------------------"));
Serial.println(F("Temperature Sensor"));
Serial.print (F("Sensor Type: ")); Serial.println(sensor.name);
Serial.print (F("Driver Ver: ")); Serial.println(sensor.version);
Serial.print (F("Unique ID: ")); Serial.println(sensor.sensor_id);
Serial.print (F("Max Value: ")); Serial.print(sensor.max_value); Serial.println(F("°C"));
Serial.print (F("Min Value: ")); Serial.print(sensor.min_value); Serial.println(F("°C"));
Serial.print (F("Resolution: ")); Serial.print(sensor.resolution); Serial.println(F("°C"));
Serial.println(F("------------------------------------"));
// Print humidity sensor details.
dht.humidity().getSensor(&sensor);
Serial.println(F("Humidity Sensor"));
Serial.print (F("Sensor Type: ")); Serial.println(sensor.name);
Serial.print (F("Driver Ver: ")); Serial.println(sensor.version);
Serial.print (F("Unique ID: ")); Serial.println(sensor.sensor_id);
Serial.print (F("Max Value: ")); Serial.print(sensor.max_value); Serial.println(F("%"));
Serial.print (F("Min Value: ")); Serial.print(sensor.min_value); Serial.println(F("%"));
Serial.print (F("Resolution: ")); Serial.print(sensor.resolution); Serial.println(F("%"));
Serial.println(F("------------------------------------"));
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 5000)
{
lastMsg = now;
char payLoad[1];
itoa(ledState, payLoad, 10);
client.publish(pubTopic, payLoad);
// Get temperature event and print its value.
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
Serial.println(F("Error reading temperature!"));
}
else {
Serial.print(F("Temperature: "));
float celsius = event.temperature;
Serial.print(celsius);
Serial.println(F("°C"));
client.publish(temperatureTopic, String(celsius).c_str());
}
// Get humidity event and print its value.
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
Serial.println(F("Error reading humidity!"));
}
else {
Serial.print(F("Humidity: "));
float humidity = event.relative_humidity;
Serial.print(humidity);
Serial.println(F("%"));
if(client.publish(humidityTopic, String(humidity).c_str())) {
Serial.println("published sucessfully");
}
else {
Serial.println("published failed");
}
}
}
}
What I can see on console output is the following:
QTT Arduino Demo
Ethernet configured via DHCP
IP address: 192.168.178.54
connecting to local MQTT broker...
connected.
------------------------------------
Temperature Sensor
Sensor Type: DHT11
Driver Ver: 1
Unique ID: -1
Max Value: 50.00°C
Min Value: 0.00°C
Resolution: 2.00°C
------------------------------------
Humidity Sensor
Sensor Type: DHT11
Driver Ver: 1
Unique ID: -1
Max Value: 80.00%
Min Value: 20.00%
Resolution: 5.00%
------------------------------------
connecting to local MQTT broker...failed, rc=-2 try again in 5 seconds
connecting to local MQTT broker...failed, rc=-2 try again in 5 seconds
connecting to local MQTT broker...failed, rc=-2 try again in 5 seconds
connecting to local MQTT broker...failed, rc=-2 try again in 5 seconds
connecting to local MQTT broker...failed, rc=-2 try again in 5 seconds
connecting to local MQTT broker...failed, rc=-2 try again in 5 seconds
and so on...
rc= - 2 ==> "network connection failed".
But the first attempt always seems to be succesfull.
I can also ping "192.168.178.54" from my windows computer and I do get an answer.
So for me it seems that there is 'something' wrong related to the ethernet connection. Any ideas?
Thanks!