Optional Argument For relay control nodemcu-32s

guys needs little help here for make optional argument in function in header file

this one is main.cpp file

#include <Arduino.h>
#include "relay.h"


void setup()
{
 relay.relaysetup(14, 27, 26);
}

void loop()
{
relay.relayloop();
}

and here another file creating function

class relay
{

private:

int Relay1;
int Relay2;
int Relay3;
int Relay4;
int Relay5;
int Relay6;
int Relay7;


public:

void relaysetup(int relay1, int relay2, int relay3, int relay4, int relay5, int relay6,
int relay7)

  {

    Relay1 = relay1;
    Relay2 = relay2;
    Relay3 = relay3;
    Relay4 = relay4;
    Relay5 = relay5;
    Relay6 = relay6;
    Relay7 = relay7;

    pinMode(Relay1, OUTPUT);
    pinMode(Relay2, OUTPUT);
    pinMode(Relay3, OUTPUT);

  }

void relayloop()
{
  digitalWrite(Relay1, LOW);
  delay(500);
  digitalWrite(Relay1, HIGH);
  delay(500);
  digitalWrite(Relay2, LOW);
  delay(500);
  digitalWrite(Relay2, HIGH);
  delay(500);
  digitalWrite(Relay3, LOW);
  delay(500);
  digitalWrite(Relay3, HIGH);
  delay(500);
}
};

relay relay;

here i declare 7 relay in function but i want to use less relay for now so how can i create optional argument in function so i can use this header file with my different project because i't too easy just include header file and than add required relays in argument in function up to seven relays

Try this. It may give you some ideas

#include <Arduino.h>

class relay
{
  private:
    int relays[7];

  public:

    void relaySetup(int relay0, int relay1 = -1, int relay2 = -1, int relay3 = -1, int relay4 = -1, int relay5 = -1, int relay6 = -1)
    {
      relays[0] = relay0;
      relays[1] = relay1;
      relays[2] = relay2;
      relays[3] = relay3;
      relays[4] = relay4;
      relays[5] = relay5;
      relays[6] = relay6;
      for (int r = 0; r < 7; r++)
      {
        if (relays[r] != -1)
        {
          pinMode(relays[r], OUTPUT);
        }
      }
    }

    void relayLoop()
    {
      Serial.println("relayLoop");
      for (int r = 0; r < 7; r++)
      {
        if (relays[r] != -1)
        {
          Serial.println(relays[r]);
        }
      }
      Serial.println();
    }
};

relay myRelays0;
relay myRelays1;

void setup()
{
  Serial.begin(115200);
  while (!Serial);
  myRelays0.relaySetup(14, 27, 26);
  myRelays1.relaySetup(10, 11, 12, 13, 14);
  myRelays0.relayLoop();
  myRelays1.relayLoop();
}

void loop()
{
}
1 Like

thank you so much buddy it's lot's help for me