4ch board module with NodeMCU turning relays ON one after another

I have 4ch board relay module with NodeMCU...when power supply is connected all 4 relays are turned ON and i would like to get scenario in which 1st relay is turned on and after 5sec 2nd relay is turned on and etc until 4th

here is the part of the code

/************************* Pin Definition *********************************/

//Relays for switching appliances
#define relay1            D0  //GPIO 16
#define relay2            D1  //GPIO 5
#define relay3            D2  //GPIO 4
#define relay4            D3  //GPIO 0
#define buzzer            26  

void setup() {
  Serial.begin(115200);

  delay(10);

  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);

 
  Serial.println(F("Adafruit MQTT demo"));

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.println("WiFi connected");
  Serial.println("IP address: "); 
  Serial.println(WiFi.localIP());
  
  // Setup MQTT subscription for onoff feed.
  mqtt.subscribe(&Light1);
  mqtt.subscribe(&Fan1);
  mqtt.subscribe(&Light2);
  mqtt.subscribe(&Fan2);
}

uint32_t x=0;

void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();
  // this is our 'wait for incoming subscription packets' busy subloop
  // try to spend your time here

  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    if (subscription == &Light1) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light1.lastread);
      int Light1_State = atoi((char *)Light1.lastread);
      digitalWrite(relay1, !Light1_State);
      
    }
    if (subscription == &Light2) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light2.lastread);
      int Light2_State = atoi((char *)Light2.lastread);
      digitalWrite(relay2, !Light2_State);
    }
    if (subscription == &Fan1) {
      Serial.print(F("Got: "));
      Serial.println((char *)Fan1.lastread);
      int Fan1_State = atoi((char *)Fan1.lastread);
      digitalWrite(relay3, !Fan1_State);
    }
    if (subscription == &Fan2) {
      Serial.print(F("Got: "));
      Serial.println((char *)Fan2.lastread);
      int Fan2_State = atoi((char *)Fan2.lastread);
      digitalWrite(relay4, !Fan2_State);
      
    }
  }

 
  // ping the server to keep the mqtt connection alive
  // NOT required if you are publishing once every KEEPALIVE seconds
  /*
    if(! mqtt.ping()) {
    mqtt.disconnect();
    }
  */
}

here's a link to what happens to the GPIO pins at boot, but keep in mind it only happens momentarily, and since the relays are opto-coupler driven & active LOW you should be able to get around it somehow, if needed using a Logic chip of some kind to provide power, but first just make sure you turn them off straight away after boot.

pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  digitalWrite(relay1, HIGH);  // the relays are 'active-LOW' which is also the default state for an output pin.
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);

Now if you want to turn them on one at the time with 5 sec intervals you should probably first create an arraty that holds the pin numbers (instead of using relay1, relaty2 it would be relay[0] etc) and then you can do something inside loop() like

static uint32_t moment = millis();
static uint8_t relaycount = 0;
if ((relaycount <4) && (millis() - moment > 5000)) {
    digitalWrite(relay[relaycount], LOW); // turn on the  relay
    relaycount++;  // swaps to the next
    moment = millis();  // reset the timer
  }

you may want to set the HIGH before configuring them as OUTPUTs

i tried this but dont know how to create array with pin numbers

byte relayPins [] = { relay1, relay2, relay3, relay4 };
#define N_RELAY_PINS sizeof(relayPins);

void
setup (void)
{
    ...
    for (unsigned n = 0; n < N_RELAY_PINS; n++)
        digitalWrite (relayPins [n], HIGH);
        pinMode (relayPins [n], OUTPUT);
    } 
    ...
}

thanks for your answer but i am beginner and dont know where to add these lines in my code:

here is my code below:

 /***************************************************
  Adafruit MQTT Library ESP8266 Example
  Must use ESP8266 Arduino from:
    https://github.com/esp8266/Arduino
  Works great with Adafruit's Huzzah ESP board & Feather
  ----> https://www.adafruit.com/product/2471
  ----> https://www.adafruit.com/products/2821
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!
  Written by Tony DiCola for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
  Code is edited by Sachin Soni for it's project called
  Ultimate Home Automation
  For Project video, visit his YouTube channel named "CreativeDesk"
 
  
 
 ****************************************************/
//for esp32 use <wifi.h> ,for esp8266 use <esp8266wifi.h>
// this code is for esp32 for using esp8266 you just need to change <wifi.h> into <esp8266wifi.h> and also change the relay pin 
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"


/************************* Pin Definition *********************************/

//Relays for switching appliances
#define relay1            D0  //GPIO 16
#define relay2            D1  //GPIO 5
#define relay3            D2  //GPIO 4
#define relay4            D3  //GPIO 0
#define buzzer            26  

//buzzer to know the status of MQTT connections and can be used for any other purpose according to your project need.


byte relayPins [] = { relay1, relay2, relay3, relay4 };
#define N_RELAY_PINS sizeof(relayPins);


   
   
/************************* WiFi Access Point *********************************/

#define WLAN_SSID       "123456"
#define WLAN_PASS       "123456"

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883                   // use 8883 for SSL
#define AIO_USERNAME    "123456"
#define AIO_KEY         "123456"

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

/****************************** Feeds ***************************************/

// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>

Adafruit_MQTT_Publish Light = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/light");


// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe Light1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/relay1");
Adafruit_MQTT_Subscribe Fan1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/relay2");
Adafruit_MQTT_Subscribe Light2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/relay3");
Adafruit_MQTT_Subscribe Fan2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/relay4");




/*************************** Sketch Code ************************************/

// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();

void setup() {
  Serial.begin(115200);

  delay(10);

  pinMode(relay1, OUTPUT);
  digitalWrite (relay1, HIGH);
  pinMode(relay2, OUTPUT);
  digitalWrite (relay2, HIGH); 
  pinMode(relay3, OUTPUT);
  digitalWrite (relay3, HIGH); 
  pinMode(relay4, OUTPUT);
  digitalWrite (relay4, HIGH);


 
  Serial.println(F("Adafruit MQTT demo"));

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.println("WiFi connected");
  Serial.println("IP address: "); 
  Serial.println(WiFi.localIP());
  
  // Setup MQTT subscription for onoff feed.
  mqtt.subscribe(&Light1);
  mqtt.subscribe(&Fan1);
  mqtt.subscribe(&Light2);
  mqtt.subscribe(&Fan2);
}

uint32_t x=0;

void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();

  
  // this is our 'wait for incoming subscription packets' busy subloop
  // try to spend your time here

  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    if (subscription == &Light1) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light1.lastread);
      int Light1_State = atoi((char *)Light1.lastread);
      digitalWrite(relay1, !Light1_State);
      
    }
    if (subscription == &Light2) {
      Serial.print(F("Got: "));
      Serial.println((char *)Light2.lastread);
      int Light2_State = atoi((char *)Light2.lastread);
      digitalWrite(relay2, !Light2_State);
    }
    if (subscription == &Fan1) {
      Serial.print(F("Got: "));
      Serial.println((char *)Fan1.lastread);
      int Fan1_State = atoi((char *)Fan1.lastread);
      digitalWrite(relay3, !Fan1_State);
    }
    if (subscription == &Fan2) {
      Serial.print(F("Got: "));
      Serial.println((char *)Fan2.lastread);
      int Fan2_State = atoi((char *)Fan2.lastread);
      digitalWrite(relay4, !Fan2_State);
      
    }
  }

 
  // ping the server to keep the mqtt connection alive
  // NOT required if you are publishing once every KEEPALIVE seconds
  /*
    if(! mqtt.ping()) {
    mqtt.disconnect();
    }
  */
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  digitalWrite(buzzer, HIGH);
  delay(200);
  digitalWrite(buzzer, LOW);
  delay(200);
  digitalWrite(buzzer, HIGH);
  delay(200);
  digitalWrite(buzzer, LOW);
  delay(200);
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
    Serial.println(mqtt.connectErrorString(ret));
    Serial.println("Retrying MQTT connection in 5 seconds...");
    mqtt.disconnect();
    delay(5000);  // wait 5 seconds
    retries--;
    if (retries == 0) {
      // basically die and wait for WDT to reset me
      while (1);
    }
  }
  Serial.println("MQTT Connected!");
  digitalWrite(buzzer, HIGH);
  delay(2000);
  digitalWrite(buzzer, LOW);
}

i added in code as you can see digitalwrite for each relay that Deva_Rishi sent it
but where should i put this part of code also sent by Deva_Rishi

static uint32_t moment = millis();
static uint8_t relaycount = 0;
if ((relaycount <4) && (millis() - moment > 5000)) {
    digitalWrite(relay[relaycount], LOW); // turn on the  relay
    relaycount++;  // swaps to the next
    moment = millis();  // reset the timer
  }

and also where to add this your code you sent :

byte relayPins [] = { relay1, relay2, relay3, relay4 };
#define N_RELAY_PINS sizeof(relayPins);

void
setup (void)
{
    ...
    for (unsigned n = 0; n < N_RELAY_PINS; n++)
        digitalWrite (relayPins [n], HIGH);
        pinMode (relayPins [n], OUTPUT);
    }
    ...
}

when power supply is connected all 4 relays are turned ON and i would like to get scenario in which 1st relay is turned on and after 5sec 2nd relay is turned on and etc until 4th

i'm becoming more confused about what you're trying to do

i guess the issue of arrays comes up because of Devi's suggestion based on your request above. But your code seems to be controlling relays based on mqtt messages, not based on any timing.

i tried this but dont know how to create array with pin numbers

i'm also confused by your response -- how could you have tried something involving arrays if you really don't understand arrays.

arrays are pretty basic programming, yet you're processing mqtt messages which suggest a more advanced understanding of programming.

it seems like you found some code that does something with relays and you want to do something with relays and have no interest in the mqtt capabilities of the code you posted.

part of what the forums can teach is not only programming but also how to describe problems and answer questions concerning what you're doing.

yes i found code on the net, and i am using adafruit.io platform or what is called to control relays

when power supply is connected all 4 relays boot up at the same time

i want to avoid this and to boot each one after another with 5 seconds apart

hope it is more clear now

don't understand why you have code supporting MQTT messaging?

// turn 4 relays on, 5 seconds apart

#define RELAY_ON    HIGH
#define RELAY_OFF   LOW

byte relayPins [] = { 10, 11, 12, 13 };
#define N_RELAY sizeof(relayPins)

unsigned long msecLst = 0;
byte          relay   = 0;

// -----------------------------------------------------------------------------
void setup (void)
{
    for (unsigned n = 0; n < N_RELAY; n++)  {
        digitalWrite (relayPins [n], RELAY_OFF);
        pinMode      (relayPins [n], OUTPUT);
    }

    msecLst = millis();
}

// -----------------------------------------------------------------------------
#define FIVE_SEC    5000
void loop (void)
{
    if (N_RELAY > relay)  {
        unsigned long msec = millis();

        if (msec - msecLst > FIVE_SEC)  {
            msecLst = msec;

            digitalWrite (relayPins [relay], RELAY_ON);
            relay++;
        }
    }
}

OK, so i figured as a global variable (array)

//Relays for switching appliances
byte relay[] = {DO, D1, D2, D3}; 

//instead of this.
/*#define relay1            D0  //GPIO 16   
#define relay2            D1  //GPIO 5
#define relay3            D2  //GPIO 4
#define relay4            D3  //GPIO 0*/
#define buzzer            26

then in setup()

for (uint8_t i = 0; i < N_4; i++) {
        digitalWrite (relay [i], HIGH);
        pinMode (relay [i], OUTPUT);
    }

(as in GJCR reply #4 though there is a '{' opening brace missing in that reply)
and in loop() (probably at the very beginning of it. but in a way anywhere will do, even in another function called from loop() is totally fine.

static uint32_t moment = millis();
static uint8_t relaycount = 0;
if ((relaycount <4) && (millis() - moment > 5000)) {
    digitalWrite(relay[relaycount], LOW); // turn on the  relay
    relaycount++;  // swaps to the next
    moment = millis();  // reset the timer
  }

thanks for your answer but i am beginner and dont know where to add these lines in my code:

i thought i did say where to add it:

and then you can do something inside loop() like

i'm becoming more confused about what you're trying to do

i guess the issue of arrays comes up because of Devi's suggestion based on your request above. But your code seems to be controlling relays based on mqtt messages, not based on any timing.

Let me explain that a little, He had a sketch to control relays using MQQT, then the dual relayboard he had was not a board that we managed to control, and when i received the new board he wrote to me in PM and i made a suggestion which worked, but also i suggested to just start a thread to find a solution for some other issues, which is where we are now.

i tried this but dont know how to create array with pin numbers

It does seem to me that you are lacking some of the basic programming skills, and it would be good if you just go through examples that show you how to do things like that.

Good luck !

Deva_Rishi:
Let me explain that a little, He had a sketch to control relays using MQQT, then the dual relayboard he had was not a board that we managed to control, and when i received the new board he wrote to me in PM and i made a suggestion which worked, but also i suggested to just start a thread to find a solution for some other issues, which is where we are now.

thanks