Relais module working, but have small problems/questions for you pro's out there :)

Hello,

Now that I got my temperature sensors working.
5 ds18B20 sensors MQTT
I am working on step two and this is the relais module.
I am using a Arduino Uno for this with W5100 ethernet shield (no wifi allowed here :slight_smile: )
I got all 8 relais working, sending 1on, 2on, 1off, 2off, ... topics will switch the relais on and off just fine.

My sketch ;

[code]
/*
 Example MQTT-switch-relay-node with 8 Relais
 
  - connects to an MQTT server
  - publishes hello message on the selected topic
  - controls 8 relais
  - turns on/off a specific relais when it receives a specific "on"/"off" from the selected topic
  - multiple arduino's with same generic sketch can run parallel to each other
  - multiple arduino's need each to have a unique ip-addres, unique mac address and unique MQTT client-ID

  - tested on arduino-uno with W5100 ethernet shield
  - Ethernet Shield W5100 uses pins 4,10,11,12,13
  - availbale digital pins: ,2,3,4,5,6,7,8,9,
*/

//------------------------------------------------------------------------------

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

// Update these with values for your MQTT client name and access information
const char* MQTTClient = "arduino1-rel"; // MQTT client name
const char* MQTTUser = "mqtt"; // MQTT client username to login to MQTT server
const char* MQTTPassword = "password"; // MQTT client user password
const char* Relais = "8-Relaisboard-1"; // Name of the topic this arduino will receive info on to control the relais
const char* RelaisState = "8-Relaisboard-1-State"; // Name of the topic this arduino will send state of the relais to
const char* welcome = "8-Relaisboard arduino 1 reporting for duty";  // bootup message that is send to the MQTT server

// Set Relais variables to Arduino digital pins
int rel1 = 2;
int rel2 = 3;
int rel3 = 4;                             // pin 1 cant be used for some reason, pin 10,11,12 and 13 used by ethernet shield W5100 on Uno
int rel4 = 5;                             // pin 4 also used by ethernet shield for SD card, works for relais only problem is it cycles one time at bootup
int rel5 = 6;
int rel6 = 7;
int rel7 = 8;
int rel8 = 9;

// Set variables to act as virtual switches
// Set variable values initially to LOW (and not HIGH)
int rel1Value = HIGH;             
int rel2Value = HIGH;
int rel3Value = HIGH;
int rel4Value = HIGH;
int rel5Value = HIGH;             
int rel6Value = HIGH;
int rel7Value = HIGH;
int rel8Value = HIGH;

//---------------------------------------------------------------------------

// Arduino MAC address is on a sticker on your Ethernet shield
// must be unique for every node in same network
// To make a new unique address change last letter

byte mac[]    = { 0xf9, 0xeb, 0xdd, 0xd5, 0xce, 0x54 };  

// Unique static IP address of this Arduino - change to adapt to your network
IPAddress ip(192,168,15,112);

// IP Address of your MQTT broker - change to adapt to your network
byte server[] = { 192, 168, 15, 101 };

// Handle and convert incoming MQTT messages ----------------------------------------

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
  String content="";
  char character;
  for (int num=0;num<length;num++) {
      character = payload[num];
      content.concat(character);
  }   
  Serial.print(topic);
  Serial.print(" : ");
  Serial.println(content); // message received from broker and serial printed


// Set specific virtual switches on basis of specific incoming messages ----------------------------
  
  if (content == "1on") {
    rel1Value = LOW;
  }
  
  if (content == "1off") {
    rel1Value = HIGH;
  }
  
  if (content == "2on") {
    rel2Value = LOW;
  }
  
  if (content == "2off") {
    rel2Value = HIGH;
  }

  
  if (content == "3on") {
    rel3Value = LOW;
  }
  
  if (content == "3off") {
    rel3Value = HIGH;
  }
  
  if (content == "4on") {
    rel4Value = LOW;
  }
  
  if (content == "4off") {
    rel4Value = HIGH;
  }

  if (content == "5on") {
    rel5Value = LOW;
  }
  
  if (content == "5off") {
    rel5Value = HIGH;
  }
  
  if (content == "6on") {
    rel6Value = LOW;
  }
  
  if (content == "6off") {
    rel6Value = HIGH;
  }

  if (content == "7on") {
    rel7Value = LOW;
  }
  
  if (content == "7off") {
    rel7Value = HIGH;
  }
  
  if (content == "8on") {
    rel8Value = LOW;
  }
  
  if (content == "8off") {
    rel8Value = HIGH;
  }
    
  // Set digital pin states according to virtual switch settings
    
  digitalWrite(rel1,rel1Value);
  digitalWrite(rel2,rel2Value);
  digitalWrite(rel3,rel3Value);
  digitalWrite(rel4,rel4Value);
  digitalWrite(rel5,rel5Value);
  digitalWrite(rel6,rel6Value);
  digitalWrite(rel7,rel7Value);
  digitalWrite(rel8,rel8Value);
}

// Initiate instances -----------------------------------

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


//-------------------------------------------------------

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection..."); // Attempt to connect
      if (client.connect(MQTTClient, MQTTUser, MQTTPassword)) {
      Serial.print("connected as MQTT client : ");
      Serial.println(MQTTClient);
      client.subscribe(Relais);                    // subscribe to topic stated above on the constants
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds - switching all relais off");
      digitalWrite(rel1,HIGH);  // for safety switch all relais off while not connected to the MQTT server
      digitalWrite(rel2,HIGH);
      digitalWrite(rel3,HIGH);
      digitalWrite(rel4,HIGH);
      digitalWrite(rel5,HIGH);
      digitalWrite(rel6,HIGH);
      digitalWrite(rel7,HIGH);
      digitalWrite(rel8,HIGH);
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}




void setup()

{

  // setup relais 1 , digitalwrite must be before pinmode to avoid cycling of relais at powerup
  digitalWrite(rel1,HIGH);
  pinMode(rel1, OUTPUT);
  
  
  // setup relais 2 -----------------------
  digitalWrite(rel2,HIGH);
  pinMode(rel2, OUTPUT);
  

  // setup relais 3 -----------------------
  digitalWrite(rel3,HIGH);
  pinMode(rel3, OUTPUT);
 

  // setup relais 4 -----------------------
  digitalWrite(rel4,HIGH);
  pinMode(rel4, OUTPUT);
  
  // setup relais 5  
  digitalWrite(rel5,HIGH);
  pinMode(rel5, OUTPUT);
  
  
  // setup relais 6 -----------------------
  digitalWrite(rel6,HIGH);
  pinMode(rel6, OUTPUT);
  

  // setup relais 7 -----------------------
  digitalWrite(rel7,HIGH);
  pinMode(rel7, OUTPUT);
 

  // setup relais 8 -----------------------
  digitalWrite(rel8,HIGH);
  pinMode(rel8, OUTPUT);

  // setup serial and ethernet communications -------------------------------

  // Setup serial connection
  Serial.begin(9600);

  // Setup ethernet connection
  Ethernet.begin(mac, ip);
  delay(500);
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
    }

//----------------------------------------------

void loop()
{
if (!client.connected()) {
    reconnect();
  }

//------------------------------------------------  
  
  client.loop();
}

// End of sketch ---------------------------------
[/code]

First I had the problem that after a power cycle all relais would activate (state LOW) and they would only start working correctly after cycling them one time.
I fixed this by adding.
digitalWrite(rel1,HIGH);
pinMode(rel1, OUTPUT);
if the digitalwrite is before the pinmode no more cycling at startup.

Now I wanted to build in some kind of safety that incase my server/internet/lan cable got compromised that the relais would automaticly deactivate (state HIGH) since they will be controlling water heaters and room heaters.

in my reconnect script I added the
digitalWrite(rel1,HIGH);
for all my relais and this indeed deactivated all relais when the arduino looses connection to the MQTT server, when I than reconnect the LAN cable, the relais stay off, but than when one command coms in (even a command to switch a relais off, ALL 8 relais get acctivated and they stay on till they all get the command to deactivate, after that they work fine again.
(so now I have the same problem again like I used to have after a power cycle)

Second problem I have ;
I want to send on regular intervalls information on another topic about the current state of the relais and I cant get this to work.
stuff I tried to use ;

long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
 if (rel1Value = HIGH) {
       client.publish(Relais2,"1isoff");								
      } else {
        client.publish(Relais2,"1ison");
      }

but im probably not using this code correctly :frowning:

3the problem/question

When powering on this arduino (or when rebooting it, activating serial monitor, ...) , the relais on pin 4 always goes active and than deactivates again.
I do realise this has something to do with PIN4 beeing used for SD card on the W5100 ethernet shield.
It is not a big problem because it simply works correctly for the rest,
but I would like to know for starters if this can hurt anything ?? (im not using the SD card)
and if this possibly could be fixed ? (can you disable all the SD card stuff on that pin ?)

Also when I say that "I have done this" and "I have made this code" I afcourse mean "I have copy/pasted this code I found all over the internet" :slight_smile:
im still a noob but slowely getting less nooby :slight_smile:

If anyone would be so kind as to look at this code and tell me how I can fix this that would be much appreciated,

thank you,

Hans

That's because you only set the output pins HIGH. You didn't set rel1Value through rel8Value HIGH. They will all be sent to the relay pins when any input arrives. Any that are LOW from the last time the relay was turned on will turn the relay on again.

You could get rid of rel1Value through rel8Value. Insted of:

  if (content == "4on") {
    rel4Value = LOW;
  }
  
  if (content == "4off") {
    rel4Value = HIGH;
  }

You could use:

  if (content == "4on") {
    digitalWrite(rel4, LOW);
  }
  
  if (content == "4off") {
    digitalWrite(rel4, HIGH);
  }

That way the relay would stay off until explicitly turned on.

@johnwasser

Awesome :slight_smile: that problem is now already fixed,
those rel1value methode was leftover because I canibalized a code I found to switch relais on/off with buttons :slight_smile:

my new code ;

[code]
/*
 Example MQTT-switch-relay-node with 8 Relais
 
  - connects to an MQTT server
  - publishes hello message on the selected topic
  - controls 8 relais
  - turns on/off a specific relais when it receives a specific "on"/"off" from the selected topic
  - multiple arduino's with same generic sketch can run parallel to each other
  - multiple arduino's need each to have a unique ip-addres, unique mac address and unique MQTT client-ID

  - tested on arduino-uno with W5100 ethernet shield
  - Ethernet Shield W5100 uses pins 4,10,11,12,13
  - availbale digital pins: ,2,3,4,5,6,7,8,9,
*/

//------------------------------------------------------------------------------

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

// Update these with values for your MQTT client name and access information
const char* MQTTClient = "arduino1-rel"; // MQTT client name
const char* MQTTUser = "mqtt"; // MQTT client username to login to MQTT server
const char* MQTTPassword = "password"; // MQTT client user password
const char* Relais = "8-Relaisboard-1"; // Name of the topic this arduino will receive info on to control the relais
const char* RelaisState = "8-Relaisboard-1-State"; // Name of the topic this arduino will send state of the relais to
const char* welcome = "8-Relaisboard arduino 1 reporting for duty";  // bootup message that is send to the MQTT server

// Set Relais variables to Arduino digital pins
int rel1 = 2;
int rel2 = 3;
int rel3 = 4;                             // pin 1 cant be used for some reason, pin 10,11,12 and 13 used by ethernet shield W5100 on Uno
int rel4 = 5;                             // pin 4 also used by ethernet shield for SD card, works for relais only problem is it cycles one time at bootup
int rel5 = 6;
int rel6 = 7;
int rel7 = 8;
int rel8 = 9;


// settings for the timed loop to report the state of the relais to the topic set in RelaisState constant
unsigned long previousMillis = 0;
const long interval = 1000; //time inbetween reporting

//---------------------------------------------------------------------------

// Arduino MAC address is on a sticker on your Ethernet shield
// must be unique for every node in same network
// To make a new unique address change last letter

byte mac[]    = { 0xf9, 0xeb, 0xdd, 0xd5, 0xce, 0x54 };  

// Unique static IP address of this Arduino - change to adapt to your network
IPAddress ip(192,168,15,112);

// IP Address of your MQTT broker - change to adapt to your network
byte server[] = { 192, 168, 15, 101 };

// Handle and convert incoming MQTT messages ----------------------------------------

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
  String content="";
  char character;
  for (int num=0;num<length;num++) {
      character = payload[num];
      content.concat(character);
  }   
  Serial.print(topic);
  Serial.print(" : ");
  Serial.println(content); // message received from broker and serial printed


// Set specific virtual switches on basis of specific incoming messages ----------------------------
  
  if (content == "1on") {
    digitalWrite(rel1, LOW);
  }
  
  if (content == "1off") {
    digitalWrite(rel1, HIGH);
  }
  
  if (content == "2on") {
    digitalWrite(rel2, LOW);
  }
  
  if (content == "2off") {
    digitalWrite(rel2, HIGH);
  }

  
  if (content == "3on") {
    digitalWrite(rel3, LOW);
  }
  
  if (content == "3off") {
    digitalWrite(rel3, HIGH);
  }
  
  if (content == "4on") {
    digitalWrite(rel4, LOW);
  }
  
  if (content == "4off") {
    digitalWrite(rel4, HIGH);
  }

  if (content == "5on") {
    digitalWrite(rel5, LOW);
  }
  
  if (content == "5off") {
    digitalWrite(rel5, HIGH);
  }
  
  if (content == "6on") {
    digitalWrite(rel6, LOW);
  }
  
  if (content == "6off") {
    digitalWrite(rel6, HIGH);
  }

  if (content == "7on") {
    digitalWrite(rel7, LOW);
  }
  
  if (content == "7off") {
    digitalWrite(rel7, HIGH);
  }
  
  if (content == "8on") {
    digitalWrite(rel8, LOW);
  }
  
  if (content == "8off") {
    digitalWrite(rel8, HIGH);
  }
    
  
}

// Initiate instances -----------------------------------

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


//-------------------------------------------------------

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection..."); // Attempt to connect
      if (client.connect(MQTTClient, MQTTUser, MQTTPassword)) {
      Serial.print("connected as MQTT client : ");
      Serial.println(MQTTClient);
      client.subscribe(Relais);                    // subscribe to topic stated above on the constants
    } else {
      digitalWrite(rel1,HIGH);
      digitalWrite(rel2,HIGH);
      digitalWrite(rel3,HIGH);
      digitalWrite(rel4,HIGH);
      digitalWrite(rel5,HIGH);
      digitalWrite(rel6,HIGH);
      digitalWrite(rel7,HIGH);
      digitalWrite(rel8,HIGH);
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds - switching all relais off");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}




void setup()

{

  // setup relais 1 , digitalwrite must be before pinmode to avoid cycling of relais at powerup
  digitalWrite(rel1,HIGH);
  pinMode(rel1, OUTPUT);
  
  
  // setup relais 2 -----------------------
  digitalWrite(rel2,HIGH);
  pinMode(rel2, OUTPUT);
  

  // setup relais 3 -----------------------
  digitalWrite(rel3,HIGH);
  pinMode(rel3, OUTPUT);
 

  // setup relais 4 -----------------------
  digitalWrite(rel4,HIGH);
  pinMode(rel4, OUTPUT);
  
  // setup relais 5  
  digitalWrite(rel5,HIGH);
  pinMode(rel5, OUTPUT);
  
  
  // setup relais 6 -----------------------
  digitalWrite(rel6,HIGH);
  pinMode(rel6, OUTPUT);
  

  // setup relais 7 -----------------------
  digitalWrite(rel7,HIGH);
  pinMode(rel7, OUTPUT);
 

  // setup relais 8 -----------------------
  digitalWrite(rel8,HIGH);
  pinMode(rel8, OUTPUT);

  // setup serial and ethernet communications -------------------------------

  // Setup serial connection
  Serial.begin(9600);

  // Setup ethernet connection
  Ethernet.begin(mac, ip);
  delay(500);
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
    }

//----------------------------------------------

void loop()
{
if (!client.connected()) {
    reconnect();
  }

//------------------------------------------------  
  
  client.loop();
}

// End of sketch ---------------------------------
[/code]

I also already added some extra code I am using with millis , and I am able to report the current state using this code

if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
 
  

   if (rel1 = LOW) {
        client.publish(RelaisState,"1stateon");                
      } else {
                client.publish(RelaisState,"1stateoff");


and that reports that 1stateoff, but it stopped the working of the relais :frowning:

ok my relais are working again now,

but it now just keeps reporting that the relais is off (even when it is on)
can anyone have one more look at my loop on the bottom to report the relais (pin) states ?
All the rest is working now,

thanks in advance,

[code]
/*
 Example MQTT-switch-relay-node with 8 Relais
 
  - connects to an MQTT server
  - publishes hello message on the selected topic
  - controls 8 relais
  - turns on/off a specific relais when it receives a specific "on"/"off" from the selected topic
  - multiple arduino's with same generic sketch can run parallel to each other
  - multiple arduino's need each to have a unique ip-addres, unique mac address and unique MQTT client-ID

  - tested on arduino-uno with W5100 ethernet shield
  - Ethernet Shield W5100 uses pins 4,10,11,12,13
  - availbale digital pins: ,2,3,4,5,6,7,8,9,
*/

//------------------------------------------------------------------------------

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

// Update these with values for your MQTT client name and access information
const char* MQTTClient = "arduino1-rel"; // MQTT client name
const char* MQTTUser = "mqtt"; // MQTT client username to login to MQTT server
const char* MQTTPassword = "password"; // MQTT client user password
const char* Relais = "8-Relaisboard-1"; // Name of the topic this arduino will receive info on to control the relais
const char* RelaisState = "8-Relaisboard-1-State"; // Name of the topic this arduino will send state of the relais to
const char* welcome = "8-Relaisboard arduino 1 reporting for duty";  // bootup message that is send to the MQTT server

// Set Relais variables to Arduino digital pins
int rel1 = 2;
int rel2 = 3;
int rel3 = 4;                             // pin 1 cant be used for some reason, pin 10,11,12 and 13 used by ethernet shield W5100 on Uno
int rel4 = 5;                             // pin 4 also used by ethernet shield for SD card, works for relais only problem is it cycles one time at bootup
int rel5 = 6;
int rel6 = 7;
int rel7 = 8;
int rel8 = 9;


// settings for the timed loop to report the state of the relais to the topic set in RelaisState constant
unsigned long previousMillis = 0;
const long interval = 1000; //time inbetween reporting

//---------------------------------------------------------------------------

// Arduino MAC address is on a sticker on your Ethernet shield
// must be unique for every node in same network
// To make a new unique address change last letter

byte mac[]    = { 0xf9, 0xeb, 0xdd, 0xd5, 0xce, 0x54 };  

// Unique static IP address of this Arduino - change to adapt to your network
IPAddress ip(192,168,15,112);

// IP Address of your MQTT broker - change to adapt to your network
byte server[] = { 192, 168, 15, 101 };

// Handle and convert incoming MQTT messages ----------------------------------------

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
  String content="";
  char character;
  for (int num=0;num<length;num++) {
      character = payload[num];
      content.concat(character);
  }   
  Serial.print(topic);
  Serial.print(" : ");
  Serial.println(content); // message received from broker and serial printed


// Set specific virtual switches on basis of specific incoming messages ----------------------------
  
  if (content == "1on") {
    digitalWrite(rel1, LOW);
  }
  
  if (content == "1off") {
    digitalWrite(rel1, HIGH);
  }
  
  if (content == "2on") {
    digitalWrite(rel2, LOW);
  }
  
  if (content == "2off") {
    digitalWrite(rel2, HIGH);
  }

  
  if (content == "3on") {
    digitalWrite(rel3, LOW);
  }
  
  if (content == "3off") {
    digitalWrite(rel3, HIGH);
  }
  
  if (content == "4on") {
    digitalWrite(rel4, LOW);
  }
  
  if (content == "4off") {
    digitalWrite(rel4, HIGH);
  }

  if (content == "5on") {
    digitalWrite(rel5, LOW);
  }
  
  if (content == "5off") {
    digitalWrite(rel5, HIGH);
  }
  
  if (content == "6on") {
    digitalWrite(rel6, LOW);
  }
  
  if (content == "6off") {
    digitalWrite(rel6, HIGH);
  }

  if (content == "7on") {
    digitalWrite(rel7, LOW);
  }
  
  if (content == "7off") {
    digitalWrite(rel7, HIGH);
  }
  
  if (content == "8on") {
    digitalWrite(rel8, LOW);
  }
  
  if (content == "8off") {
    digitalWrite(rel8, HIGH);
  }
    
  
}

// Initiate instances -----------------------------------

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


//-------------------------------------------------------

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection..."); // Attempt to connect
      if (client.connect(MQTTClient, MQTTUser, MQTTPassword)) {
      Serial.print("connected as MQTT client : ");
      Serial.println(MQTTClient);
      client.subscribe(Relais);                    // subscribe to topic stated above on the constants
    } else {
      digitalWrite(rel1,HIGH);
      digitalWrite(rel2,HIGH);
      digitalWrite(rel3,HIGH);
      digitalWrite(rel4,HIGH);
      digitalWrite(rel5,HIGH);
      digitalWrite(rel6,HIGH);
      digitalWrite(rel7,HIGH);
      digitalWrite(rel8,HIGH);
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds - switching all relais off");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}




void setup()

{

  // setup relais 1 , digitalwrite must be before pinmode to avoid cycling of relais at powerup
  digitalWrite(rel1,HIGH);
  pinMode(rel1, OUTPUT);
  
  
  // setup relais 2 -----------------------
  digitalWrite(rel2,HIGH);
  pinMode(rel2, OUTPUT);
  

  // setup relais 3 -----------------------
  digitalWrite(rel3,HIGH);
  pinMode(rel3, OUTPUT);
 

  // setup relais 4 -----------------------
  digitalWrite(rel4,HIGH);
  pinMode(rel4, OUTPUT);
  
  // setup relais 5  
  digitalWrite(rel5,HIGH);
  pinMode(rel5, OUTPUT);
  
  
  // setup relais 6 -----------------------
  digitalWrite(rel6,HIGH);
  pinMode(rel6, OUTPUT);
  

  // setup relais 7 -----------------------
  digitalWrite(rel7,HIGH);
  pinMode(rel7, OUTPUT);
 

  // setup relais 8 -----------------------
  digitalWrite(rel8,HIGH);
  pinMode(rel8, OUTPUT);

  // setup serial and ethernet communications -------------------------------

  // Setup serial connection
  Serial.begin(9600);

  // Setup ethernet connection
  Ethernet.begin(mac, ip);
  delay(500);
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
    }

//----------------------------------------------

void loop()
{
if (!client.connected()) {
    reconnect();
  }
 unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
 
     if (rel1 == LOW) {
        client.publish(RelaisState,"1stateon");                
      } else {
                client.publish(RelaisState,"1stateoff");

      }
}
//------------------------------------------------  
  
  client.loop();
}

// End of sketch ---------------------------------
[/code]

I don't see any use of the analogPins. To get round the issue with Pin 4, you can e.g. pin 14 as a digital output.

Oh, thanks for the tip, I dident know I could also use those pins for my relais :slightly_smiling_face:

Ill dig in to that a bit also than :slight_smile:

thanks for the tip.

Hans

WARNING: The '=' operator is for assignment. You probably want the comparison operator: '=='

I already found that = and == earlyer and fixed it :slight_smile:

I actualy got it working now , it is reporting the state of relais 1 every second and I can still switch,
now is there a way to ONLY report the state when anything changed ???

my code now

[code]
/*
 Example MQTT-switch-relay-node with 8 Relais
 
  - connects to an MQTT server
  - publishes hello message on the selected topic
  - controls 8 relais
  - turns on/off a specific relais when it receives a specific "on"/"off" from the selected topic
  - multiple arduino's with same generic sketch can run parallel to each other
  - multiple arduino's need each to have a unique ip-addres, unique mac address and unique MQTT client-ID

  - tested on arduino-uno with W5100 ethernet shield
  - Ethernet Shield W5100 uses pins 4,10,11,12,13
  - availbale digital pins: ,2,3,4,5,6,7,8,9,
*/

//------------------------------------------------------------------------------

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

// Update these with values for your MQTT client name and access information
const char* MQTTClient = "arduino1-rel"; // MQTT client name
const char* MQTTUser = "mqtt"; // MQTT client username to login to MQTT server
const char* MQTTPassword = "Password"; // MQTT client user password
const char* Relais = "8-Relaisboard-1"; // Name of the topic this arduino will receive info on to control the relais
const char* RelaisState = "8-Relaisboard-1-State"; // Name of the topic this arduino will send state of the relais to
const char* welcome = "8-Relaisboard arduino 1 reporting for duty";  // bootup message that is send to the MQTT server

// Set Relais variables to Arduino digital pins
int rel1 = 2;
int rel2 = 3;
int rel3 = 4;                             // pin 1 cant be used for some reason, pin 10,11,12 and 13 used by ethernet shield W5100 on Uno
int rel4 = 5;                             // pin 4 also used by ethernet shield for SD card, works for relais only problem is it cycles one time at bootup
int rel5 = 6;
int rel6 = 7;
int rel7 = 8;
int rel8 = 9;

int relais1Last = 0; // does digitalRead return an int? Whatever the appropriate data type and whereever it is appropriate so the value is preserved for each time through the loop
int relais1Curr = 0;


// settings for the timed loop to report the state of the relais to the topic set in RelaisState constant
unsigned long previousMillis = 0;
const long interval = 1000; //time inbetween reporting

//---------------------------------------------------------------------------

// Arduino MAC address is on a sticker on your Ethernet shield
// must be unique for every node in same network
// To make a new unique address change last letter

byte mac[]    = { 0xf9, 0xeb, 0xdd, 0xd5, 0xce, 0x54 };  

// Unique static IP address of this Arduino - change to adapt to your network
IPAddress ip(192,168,15,112);

// IP Address of your MQTT broker - change to adapt to your network
byte server[] = { 192, 168, 15, 101 };

// Handle and convert incoming MQTT messages ----------------------------------------

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
  String content="";
  char character;
  for (int num=0;num<length;num++) {
      character = payload[num];
      content.concat(character);
  }   
  Serial.print(topic);
  Serial.print(" : ");
  Serial.println(content); // message received from broker and serial printed


// Set specific virtual switches on basis of specific incoming messages ----------------------------
  
  if (content == "1on") {
    digitalWrite(rel1, LOW);
  }
  
  if (content == "1off") {
    digitalWrite(rel1, HIGH);
  }
  
  if (content == "2on") {
    digitalWrite(rel2, LOW);
  }
  
  if (content == "2off") {
    digitalWrite(rel2, HIGH);
  }

  
  if (content == "3on") {
    digitalWrite(rel3, LOW);
  }
  
  if (content == "3off") {
    digitalWrite(rel3, HIGH);
  }
  
  if (content == "4on") {
    digitalWrite(rel4, LOW);
  }
  
  if (content == "4off") {
    digitalWrite(rel4, HIGH);
  }

  if (content == "5on") {
    digitalWrite(rel5, LOW);
  }
  
  if (content == "5off") {
    digitalWrite(rel5, HIGH);
  }
  
  if (content == "6on") {
    digitalWrite(rel6, LOW);
  }
  
  if (content == "6off") {
    digitalWrite(rel6, HIGH);
  }

  if (content == "7on") {
    digitalWrite(rel7, LOW);
  }
  
  if (content == "7off") {
    digitalWrite(rel7, HIGH);
  }
  
  if (content == "8on") {
    digitalWrite(rel8, LOW);
  }
  
  if (content == "8off") {
    digitalWrite(rel8, HIGH);
  }
    
  
}

// Initiate instances -----------------------------------

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


//-------------------------------------------------------

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection..."); // Attempt to connect
      if (client.connect(MQTTClient, MQTTUser, MQTTPassword)) {
      Serial.print("connected as MQTT client : ");
      Serial.println(MQTTClient);
      client.subscribe(Relais);                    // subscribe to topic stated above on the constants
    } else {
      digitalWrite(rel1,HIGH);
      digitalWrite(rel2,HIGH);
      digitalWrite(rel3,HIGH);
      digitalWrite(rel4,HIGH);
      digitalWrite(rel5,HIGH);
      digitalWrite(rel6,HIGH);
      digitalWrite(rel7,HIGH);
      digitalWrite(rel8,HIGH);
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds - switching all relais off");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}




void setup()

{

  // setup relais 1 , digitalwrite must be before pinmode to avoid cycling of relais at powerup
  digitalWrite(rel1,HIGH);
  pinMode(rel1, OUTPUT);
  
  
  // setup relais 2 -----------------------
  digitalWrite(rel2,HIGH);
  pinMode(rel2, OUTPUT);
  

  // setup relais 3 -----------------------
  digitalWrite(rel3,HIGH);
  pinMode(rel3, OUTPUT);
 

  // setup relais 4 -----------------------
  digitalWrite(rel4,HIGH);
  pinMode(rel4, OUTPUT);
  
  // setup relais 5  
  digitalWrite(rel5,HIGH);
  pinMode(rel5, OUTPUT);
  
  
  // setup relais 6 -----------------------
  digitalWrite(rel6,HIGH);
  pinMode(rel6, OUTPUT);
  

  // setup relais 7 -----------------------
  digitalWrite(rel7,HIGH);
  pinMode(rel7, OUTPUT);
 

  // setup relais 8 -----------------------
  digitalWrite(rel8,HIGH);
  pinMode(rel8, OUTPUT);

  // setup serial and ethernet communications -------------------------------

  // Setup serial connection
  Serial.begin(9600);

  // Setup ethernet connection
  Ethernet.begin(mac, ip);
  delay(500);
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
    }

//----------------------------------------------

void loop()
{
if (!client.connected()) {
    reconnect();
  }
 unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
 
     // Did Relais1 change state?
    relais1Curr = digitalRead(rel1);
    
    if(relais1Curr != relais1Last); {
    relais1Last = relais1Curr;
    if(relais1Curr == LOW) client.publish(RelaisState,"1ison");
    else client.publish(RelaisState,"1isoff");
    } }   



//------------------------------------------------  
  
  client.loop();
}

// End of sketch ---------------------------------
[/code]

When you have three or more variables that have the same name except with sequential numbers, it's time to learn how to use arrays. The sketch goes from 293 lines to 152 so almost half the size.

Here is a quick edit showing the kind of changes to make:

/*
  Example MQTT-switch-relay-node with 8 Relais

  - connects to an MQTT server
  - publishes hello message on the selected topic
  - controls 8 relais
  - turns on/off a specific relais when it receives a specific "on"/"off" from the selected topic
  - multiple arduino's with same generic sketch can run parallel to each other
  - multiple arduino's need each to have a unique ip-addres, unique mac address and unique MQTT client-ID

  - tested on arduino-uno with W5100 ethernet shield
  - Ethernet Shield W5100 uses pins 4,10,11,12,13
  - availbale digital pins: ,2,3,4,5,6,7,8,9,
*/

//------------------------------------------------------------------------------

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

// Update these with values for your MQTT client name and access information
const char* MQTTClient = "arduino1-rel"; // MQTT client name
const char* MQTTUser = "mqtt"; // MQTT client username to login to MQTT server
const char* MQTTPassword = "password"; // MQTT client user password
const char* Relais = "8-Relaisboard-1"; // Name of the topic this arduino will receive info on to control the relais
const char* RelaisState = "8-Relaisboard-1-State"; // Name of the topic this arduino will send state of the relais to
const char* welcome = "8-Relaisboard arduino 1 reporting for duty";  // bootup message that is send to the MQTT server

// Set Relais variables to Arduino digital pins
byte RelayPins[8] = {2, 3, 4, 5, 6, 7, 8, 9};

// settings for the timed loop to report the state of the relais to the topic set in RelaisState constant
unsigned long previousMillis = 0;
const long interval = 1000; //time inbetween reporting

//---------------------------------------------------------------------------

// Arduino MAC address is on a sticker on your Ethernet shield
// must be unique for every node in same network
// To make a new unique address change last letter

byte mac[]    = { 0xf9, 0xeb, 0xdd, 0xd5, 0xce, 0x54 };

// Unique static IP address of this Arduino - change to adapt to your network
IPAddress ip(192, 168, 15, 112);

// IP Address of your MQTT broker - change to adapt to your network
byte server[] = { 192, 168, 15, 101 };

// Handle and convert incoming MQTT messages ----------------------------------------

void callback(char* topic, byte* payload, unsigned int length)
{
  // handle message arrived
  String content = "";
  char character;
  for (int num = 0; num < length; num++)
  {
    character = payload[num];
    content.concat(character);
  }
  Serial.print(topic);
  Serial.print(" : ");
  Serial.println(content); // message received from broker and serial printed

  // Set specific virtual switches on basis of specific incoming messages ----------------------------
  char pin = content[0];
  if (pin >= '1' && pin <= '8')
  {
    if (content.endsWith("on"))
    {
      digitalWrite(RelayPins[pin - '1'], LOW);
    }

    if (content.endsWith("off"))
    {
      digitalWrite(RelayPins[RelayPins[pin - '1'], HIGH);
    }
  }
}

// Initiate instances -----------------------------------

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


//-------------------------------------------------------

void reconnect()
{
  // Loop until we're reconnected
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection..."); // Attempt to connect
    if (client.connect(MQTTClient, MQTTUser, MQTTPassword))
    {
      Serial.print("connected as MQTT client : ");
      Serial.println(MQTTClient);
      client.subscribe(Relais);                    // subscribe to topic stated above on the constants
    }
    else
    {
      for (int i = 0; i < 8; i++)
      {
        digitalWrite(RelayPins[i], HIGH);
      }
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds - switching all relais off");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup()
{
  for (int i = 0; i < 8; i++)
  {
    // digitalWrite() must be before pinmode to avoid cycling of relais at powerup
    digitalWrite(RelayPins[i], HIGH);
    pinMode(RelayPins[i], OUTPUT);
  }

  // setup serial and ethernet communications -------------------------------

  // Setup serial connection
  Serial.begin(9600);

  // Setup ethernet connection
  Ethernet.begin(mac, ip);
  delay(500);
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

//----------------------------------------------

void loop()
{
  if (!client.connected())
  {
    reconnect();
  }

  //------------------------------------------------

  client.loop();
}
// End of sketch ---------------------------------

wow,

Ill defenatly will have to look in to that array thing , but for the moment thats almost chinese to me :slight_smile:

I will for sure try to shrink my code that way.

for the moment, only thing I aint got working now is that the arduino will only report the state of the relais if they have actualy changed.

I am trying this ; but it just keeps sending the state every 1000millis (and not only if they changed)
gues im still even strugling with the if/else thing :slight_smile:

void loop()
{
if (!client.connected()) {
    reconnect();
  }
 unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
 
     // Did Relais1 change state?
    relais1Curr = digitalRead(rel1);
    
    if(relais1Curr != relais1Last);
    {relais1Last = relais1Curr;
    if(relais1Curr == LOW) client.publish(RelaisState,"1ison");
    else client.publish(RelaisState,"1isoff");
    }
    else
{
}
}  



//------------------------------------------------  
  
  client.loop();
}

Unless it causes a problem with MQTT, I would forget about keeping status variables and just send a message from the callback whenever you actually digitalWrite to a relay pin.

@wildbill that actually does seem the way to go,

think I will re-write the sketch to send a status update to the status topic when the relais switches and than just keep reporting the state of the relais every 10mins or so for confirmation.

When I get it all working, ill defenatly look in to using those array's to schrink the sketch.

thanks alot everyone for your help and tips,

Hans

Ok, I tought this was gona be easy now, gues not :frowning:

If I add stuff like this ;

 if (content == "1on") {
    digitalWrite(rel1, LOW);
    client.publish(RelaisState, "1ison");
  }

while compiling I get the error "'client' was not declared in this scope"

but when I dare move my

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

Up above the new publish, I get the same error but this time for the last line

  client.loop();

that it say's that one is not declared ??

Im sure this is gona be very logic to some of you pro's but im stumped :frowning:

Move those two definitions up above all your functions.

@wildbill

I tried :frowning:
when I put them above the callback part I get the same error that now the "callback" is not defined.
If I put it below the callback part and above the part with the new publish it say's the Client from
Client.loop way back at my sketch is not defined :frowning:

I gues its some kind of catch22 thing ??

I expect a manual prototype will take care of it. Post your latest attempt.

This one says the client at the end (client.loop) is not defined now

[code]
/*
 Example MQTT-switch-relay-node with 8 Relais
 
  - connects to an MQTT server
  - publishes hello message on the selected topic
  - controls 8 relais
  - turns on/off a specific relais when it receives a specific "on"/"off" from the selected topic
  - multiple arduino's with same generic sketch can run parallel to each other
  - multiple arduino's need each to have a unique ip-addres, unique mac address and unique MQTT client-ID

  - tested on arduino-uno with W5100 ethernet shield
  - Ethernet Shield W5100 uses pins 4,10,11,12,13
  - availbale digital pins: ,2,3,4,5,6,7,8,9,
*/

//------------------------------------------------------------------------------

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



// Update these with values for your MQTT client name and access information
const char* MQTTClient = "arduino1-rel"; // MQTT client name
const char* MQTTUser = "mqtt"; // MQTT client username to login to MQTT server
const char* MQTTPassword = "password"; // MQTT client user password
const char* Relais = "8-Relaisboard-1"; // Name of the topic this arduino will receive info on to control the relais
const char* RelaisState = "8-Relaisboard-1-State"; // Name of the topic this arduino will send state of the relais to
const char* welcome = "8-Relaisboard arduino 1 reporting for duty";  // bootup message that is send to the MQTT server

// Set Relais variables to Arduino digital pins
int rel1 = 2;
int rel2 = 3;
int rel3 = 4;                             // pin 1 cant be used for some reason, pin 10,11,12 and 13 used by ethernet shield W5100 on Uno
int rel4 = 5;                             // pin 4 also used by ethernet shield for SD card, works for relais only problem is it cycles one time at bootup
int rel5 = 6;
int rel6 = 7;
int rel7 = 8;
int rel8 = 9;



// settings for the timed loop to report the state of the relais to the topic set in RelaisState constant
unsigned long previousMillis = 0;
const long interval = 10000; //time inbetween reporting

//---------------------------------------------------------------------------

// Arduino MAC address is on a sticker on your Ethernet shield
// must be unique for every node in same network
// To make a new unique address change last letter

byte mac[]    = { 0xf9, 0xeb, 0xdd, 0xd5, 0xce, 0x54 };  

// Unique static IP address of this Arduino - change to adapt to your network
IPAddress ip(192,168,15,112);

// IP Address of your MQTT broker - change to adapt to your network
byte server[] = { 192, 168, 15, 101 };




// Handle and convert incoming MQTT messages ----------------------------------------

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
  String content="";
  char character;
  for (int num=0;num<length;num++) {
      character = payload[num];
      content.concat(character);
  }   
  Serial.print(topic);
  Serial.print(" : ");
  Serial.println(content); // message received from broker and serial printed

// Initiate instances -----------------------------------

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

// Set specific virtual switches on basis of specific incoming messages ----------------------------
  
  if (content == "1on") {
    digitalWrite(rel1, LOW);
    client.publish(RelaisState, "1ison");
  }
  
  if (content == "1off") {
    digitalWrite(rel1, HIGH);
    client.publish(RelaisState, "1isoff");
  }
  
  if (content == "2on") {
    digitalWrite(rel2, LOW);
  }
  
  if (content == "2off") {
    digitalWrite(rel2, HIGH);
  }

  
  if (content == "3on") {
    digitalWrite(rel3, LOW);
  }
  
  if (content == "3off") {
    digitalWrite(rel3, HIGH);
  }
  
  if (content == "4on") {
    digitalWrite(rel4, LOW);
  }
  
  if (content == "4off") {
    digitalWrite(rel4, HIGH);
  }

  if (content == "5on") {
    digitalWrite(rel5, LOW);
  }
  
  if (content == "5off") {
    digitalWrite(rel5, HIGH);
  }
  
  if (content == "6on") {
    digitalWrite(rel6, LOW);
  }
  
  if (content == "6off") {
    digitalWrite(rel6, HIGH);
  }

  if (content == "7on") {
    digitalWrite(rel7, LOW);
  }
  
  if (content == "7off") {
    digitalWrite(rel7, HIGH);
  }
  
  if (content == "8on") {
    digitalWrite(rel8, LOW);
  }
  
  if (content == "8off") {
    digitalWrite(rel8, HIGH);
  }
    
  
}




//-------------------------------------------------------

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection..."); // Attempt to connect
      if (client.connect(MQTTClient, MQTTUser, MQTTPassword)) {
      Serial.print("connected as MQTT client : ");
      Serial.println(MQTTClient);
      client.subscribe(Relais);                    // subscribe to topic stated above on the constants
    } else {
      digitalWrite(rel1,HIGH);
      digitalWrite(rel2,HIGH);
      digitalWrite(rel3,HIGH);
      digitalWrite(rel4,HIGH);
      digitalWrite(rel5,HIGH);
      digitalWrite(rel6,HIGH);
      digitalWrite(rel7,HIGH);
      digitalWrite(rel8,HIGH);
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds - switching all relais off");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}




void setup()

{

  // setup relais 1 , digitalwrite must be before pinmode to avoid cycling of relais at powerup
  digitalWrite(rel1,HIGH);
  pinMode(rel1, OUTPUT);
  
  
  // setup relais 2 -----------------------
  digitalWrite(rel2,HIGH);
  pinMode(rel2, OUTPUT);
  

  // setup relais 3 -----------------------
  digitalWrite(rel3,HIGH);
  pinMode(rel3, OUTPUT);
 

  // setup relais 4 -----------------------
  digitalWrite(rel4,HIGH);
  pinMode(rel4, OUTPUT);
  
  // setup relais 5  
  digitalWrite(rel5,HIGH);
  pinMode(rel5, OUTPUT);
  
  
  // setup relais 6 -----------------------
  digitalWrite(rel6,HIGH);
  pinMode(rel6, OUTPUT);
  

  // setup relais 7 -----------------------
  digitalWrite(rel7,HIGH);
  pinMode(rel7, OUTPUT);
 

  // setup relais 8 -----------------------
  digitalWrite(rel8,HIGH);
  pinMode(rel8, OUTPUT);

  // setup serial and ethernet communications -------------------------------

  // Setup serial connection
  Serial.begin(9600);

  // Setup ethernet connection
  Ethernet.begin(mac, ip);
  delay(500);
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
    }

//----------------------------------------------

void loop()
{
if (!client.connected()) {
    reconnect();
  }
 unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    
}  



//------------------------------------------------  
  
  client.loop();
}

// End of sketch ---------------------------------
[/code]

Try this:

// Handle and convert incoming MQTT messages ----------------------------------------
void callback(char* topic, byte* payload, unsigned int length);

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

void callback(char* topic, byte* payload, unsigned int length)
{
  // handle message arrived
  String content = "";
.
.
.

@wildbill

That works !!!!

I tought I could not put those things in twice (had problems with doing that before)

Thanks so much for all the help and especialy the patience :slight_smile:

Im sure ill be back with the next problem soon :slight_smile:

EDIT : im back already, when I put in the code for all 8 relais, the arduino constantly looses connection to the mqtt server and does not work, gues it cant handle it all :frowning:
ill probably have to indeed cut back on my code for all this to work :frowning:

EDIT 2 : when I put the millis to every 5 minutes to report it seems to be working, it was now set to every second and gues that was the problem to handle it ?

again, thanks for all the help.

Hello,

Just posting my final sketch (not simplified yet with array's),

So this works in controlling 8 relais with MQTT, also reports the relais state on another topic at switching and reports the current state on that topic every 5 minutes.

I have also switched one relais from pin4 (problem with cycling because of ethernet shield SD) to analog A0 (pin14) so also no more cycling at startup, all problems fixed :slight_smile:

thank you all for the help and tips,

ill post sketch for other people to use ;

[code]
/*
 Example MQTT-switch-relay-node with 8 Relais
 
  - connects to an MQTT server
  - publishes hello message on the selected topic
  - controls 8 relais
  - turns on/off a specific relais when it receives a specific "on"/"off" from the selected topic
  - multiple arduino's with same generic sketch can run parallel to each other
  - multiple arduino's need each to have a unique ip-addres, unique mac address and unique MQTT client-ID

  - tested on arduino-uno with W5100 ethernet shield
  - Ethernet Shield W5100 uses pins 4,10,11,12,13
  - availbale digital pins: ,2,3,4,5,6,7,8,9,
*/

//------------------------------------------------------------------------------

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



// Update these with values for your MQTT client name and access information
const char* MQTTClient = "arduino1-rel"; // MQTT client name
const char* MQTTUser = "mqtt"; // MQTT client username to login to MQTT server
const char* MQTTPassword = "Password"; // MQTT client user password
const char* Relais = "8-Relaisboard-1"; // Name of the topic this arduino will receive info on to control the relais
const char* RelaisState = "8-Relaisboard-1-State"; // Name of the topic this arduino will send state of the relais to
const char* welcome = "8-Relaisboard arduino 1 reporting for duty";  // bootup message that is send to the MQTT server

// Set Relais variables to Arduino digital pins
int rel1 = 2;
int rel2 = 3;
int rel3 = 5;                             // pin 1 cant be used for some reason, pin 10,11,12 and 13 used by ethernet shield W5100 on Uno
int rel4 = 6;                             // pin 4 also used by ethernet shield for SD card, works for relais only problem is it cycles one time at bootup
int rel5 = 7;                             // analog pins A0 - A5 (pin 14 - 19) can also be used for digitalWrite functions
int rel6 = 8;
int rel7 = 9;
int rel8 = 14;



// settings for the timed loop to report the state of the relais to the topic set in RelaisState constant
unsigned long previousMillis = 0;
const long interval = 300000; //time inbetween reporting , set to every 5 minutes now

//---------------------------------------------------------------------------

// Arduino MAC address is on a sticker on your Ethernet shield
// must be unique for every node in same network
// To make a new unique address change last letter

byte mac[]    = { 0xf9, 0xeb, 0xdd, 0xd5, 0xce, 0x54 };  

// Unique static IP address of this Arduino - change to adapt to your network
IPAddress ip(192,168,15,112);

// IP Address of your MQTT broker - change to adapt to your network
byte server[] = { 192, 168, 15, 101 };




// Handle and convert incoming MQTT messages ----------------------------------------

void callback(char* topic, byte* payload, unsigned int length);

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

void callback(char* topic, byte* payload, unsigned int length)
{
  // handle message arrived
  String content="";
  char character;
  for (int num=0;num<length;num++) {
      character = payload[num];
      content.concat(character);
  }   
  Serial.print(topic);
  Serial.print(" : ");
  Serial.println(content); // message received from broker and serial printed


// Set specific virtual switches on basis of specific incoming messages ----------------------------
  
  if (content == "1on") {
    digitalWrite(rel1, LOW);
    client.publish(RelaisState, "1ison");
  }
  
  if (content == "1off") {
    digitalWrite(rel1, HIGH);
    client.publish(RelaisState, "1isoff");
  }
  
  if (content == "2on") {
    digitalWrite(rel2, LOW);
    client.publish(RelaisState, "2ison");
  }
  
  if (content == "2off") {
    digitalWrite(rel2, HIGH);
    client.publish(RelaisState, "2isoff");
  }

  
  if (content == "3on") {
    digitalWrite(rel3, LOW);
    client.publish(RelaisState, "3ison");
  }
  
  if (content == "3off") {
    digitalWrite(rel3, HIGH);
    client.publish(RelaisState, "3isoff");
  }
  
  if (content == "4on") {
    digitalWrite(rel4, LOW);
    client.publish(RelaisState, "4ison");
  }
  
  if (content == "4off") {
    digitalWrite(rel4, HIGH);
    client.publish(RelaisState, "4isoff");
  }

  if (content == "5on") {
    digitalWrite(rel5, LOW);
    client.publish(RelaisState, "5ison");
  }
  
  if (content == "5off") {
    digitalWrite(rel5, HIGH);
    client.publish(RelaisState, "5isoff");
  }
  
  if (content == "6on") {
    digitalWrite(rel6, LOW);
    client.publish(RelaisState, "6ison");
  }
  
  if (content == "6off") {
    digitalWrite(rel6, HIGH);
    client.publish(RelaisState, "6isoff");
  }

  if (content == "7on") {
    digitalWrite(rel7, LOW);
    client.publish(RelaisState, "7ison");
  }
  
  if (content == "7off") {
    digitalWrite(rel7, HIGH);
    client.publish(RelaisState, "7isoff");
  }
  
  if (content == "8on") {
    digitalWrite(rel8, LOW);
    client.publish(RelaisState, "8ison");
  }
  
  if (content == "8off") {
    digitalWrite(rel8, HIGH);
    client.publish(RelaisState, "8isoff");
  }
    
  
}




//-------------------------------------------------------

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection..."); // Attempt to connect
      if (client.connect(MQTTClient, MQTTUser, MQTTPassword)) {
      Serial.print("connected as MQTT client : ");
      Serial.println(MQTTClient);
      client.subscribe(Relais);                    // subscribe to topic stated above on the constants
    } else {
      digitalWrite(rel1,HIGH);
      digitalWrite(rel2,HIGH);
      digitalWrite(rel3,HIGH);
      digitalWrite(rel4,HIGH);
      digitalWrite(rel5,HIGH);
      digitalWrite(rel6,HIGH);
      digitalWrite(rel7,HIGH);
      digitalWrite(rel8,HIGH);
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds - switching all relais off");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}




void setup()

{

  // setup relais 1 , digitalwrite must be before pinmode to avoid cycling of relais at powerup
  digitalWrite(rel1,HIGH);
  pinMode(rel1, OUTPUT);
  
  
  // setup relais 2 -----------------------
  digitalWrite(rel2,HIGH);
  pinMode(rel2, OUTPUT);
  

  // setup relais 3 -----------------------
  digitalWrite(rel3,HIGH);
  pinMode(rel3, OUTPUT);
 

  // setup relais 4 -----------------------
  digitalWrite(rel4,HIGH);
  pinMode(rel4, OUTPUT);
  
  // setup relais 5  
  digitalWrite(rel5,HIGH);
  pinMode(rel5, OUTPUT);
  
  
  // setup relais 6 -----------------------
  digitalWrite(rel6,HIGH);
  pinMode(rel6, OUTPUT);
  

  // setup relais 7 -----------------------
  digitalWrite(rel7,HIGH);
  pinMode(rel7, OUTPUT);
 

  // setup relais 8 -----------------------
  digitalWrite(rel8,HIGH);
  pinMode(rel8, OUTPUT);

  // setup serial and ethernet communications -------------------------------

  // Setup serial connection
  Serial.begin(9600);

  // Setup ethernet connection
  Ethernet.begin(mac, ip);
  delay(500);
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
    }

//----------------------------------------------

void loop()
{
if (!client.connected()) {
    reconnect();
  }
 unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
if (digitalRead(rel1) == LOW){
client.publish(RelaisState, "1ison");
}
else {
client.publish(RelaisState, "1isoff");
}    
if (digitalRead(rel2) == LOW){
client.publish(RelaisState, "2ison");
}
else {
client.publish(RelaisState, "2isoff");
}  
if (digitalRead(rel3) == LOW){
client.publish(RelaisState, "3ison");
}
else {
client.publish(RelaisState, "3isoff");
}  
if (digitalRead(rel4) == LOW){
client.publish(RelaisState, "4ison");
}
else {
client.publish(RelaisState, "4isoff");
}  
if (digitalRead(rel5) == LOW){
client.publish(RelaisState, "5ison");
}
else {
client.publish(RelaisState, "5isoff");
}  
if (digitalRead(rel6) == LOW){
client.publish(RelaisState, "6ison");
}
else {
client.publish(RelaisState, "6isoff");
} 
if (digitalRead(rel7) == LOW){
client.publish(RelaisState, "7ison");
}
else {
client.publish(RelaisState, "7isoff");
}  
if (digitalRead(rel8) == LOW){
client.publish(RelaisState, "8ison");
}
else {
client.publish(RelaisState, "8isoff");
}  
}  

//------------------------------------------------  
  
  client.loop();
}

// End of sketch ---------------------------------
[/code]