Hi! I use an Arduino mega with w5500 eth shield. I wrote this code to receive mqtt messages from openhab. The MQTT and the openhab works well but when i send an on command to this topic the output simply switch up and then down. for the off command the same thing happens. then i realized that it doesn't matter which topic receive the message the pin goes up and down when an mqtt messega received. What did I wrote wrong?
#include <SPI.h>
#include <Ethernet2.h>
#include <PubSubClient.h>
#include <Wire.h>
unsigned long interval=5000; // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.
int erkl = 13;
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
byte server[] = { 172, 16, 10, 105 };
byte ip[] = { 172, 16, 10, 214 };
void callback(char* topic, byte* payload, unsigned int length);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
Ethernet.begin(mac, ip);
if (client.connect("arduinoClient")) {
client.publish("outTopic","hello world");
client.subscribe("/mega/#");
}
}
void loop()
{
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
char receivedChar;
Serial.println();
Serial.println("Callback");
Serial.print("Topic ");
Serial.println(topic);
Serial.print("Length ");
Serial.println(length);
Serial.print("Payload ");
for (int i=0;i<length;i++) {
receivedChar = (char)payload[i];
Serial.print(receivedChar);}
Serial.println();
if (topic == "/mega/erkl/1/com") {
if (payload[0] == '0')
{
digitalWrite(erkl, LOW);
//delay(100);
//client.publish("/mega/erkl/1/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(erkl, HIGH);
//delay(100);
//client.publish("/mega/erkl/1/state","1");
}
}
if (receivedChar == '0')
{
digitalWrite(erkl, LOW);
delay(100);
//client.publish("/mega/erkl/1/state","0");
}
if (receivedChar == '1')
{
digitalWrite(erkl, HIGH);
delay(100);
//client.publish("/mega/erkl/1/state","1");
}
}