Hi everyone, I'm experimenting with the PubSubClient library for the MQTT protocol.
I started from the example sketch and added three simple instructions to turn on a relay connected to PIN 12 when a message is received. From the serial monitor I can see that the client is correctly subscribed to the topic and it is receiving all the messages, however the relay does not turn on. I used this simple script
void setup() {
pinMode(12, OUTPUT);
}
void loop() {
digitalWrite(12, HIGH);
delay(3000);
digitalWrite(12, LOW);
delay(7000);
}
to check if everything is wired correctly and it works. Can you help me in understanding what I am doing wrong? here is the code that I'm executing:
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
const int MY_PIN = 12;
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 77);
IPAddress server(192, 168, 1, 248);
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++) {
Serial.print((char)payload[i]);
}
digitalWrite(MY_PIN, HIGH);
delay(5000);
digitalWrite(MY_PIN, LOW);
Serial.println("END CALLBACK");
}
EthernetClient ethClient;
PubSubClient client(ethClient);
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic","hello world");
// ... and resubscribe
client.subscribe("/hello");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(9600);
pinMode(MY_PIN, OUTPUT);
client.setServer(server, 1883);
client.setCallback(callback);
Ethernet.begin(mac, ip);
// Allow the hardware to sort itself out
delay(1500);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}