Two channel relays custom timing [code example]

Hi all,
It's my first post here :slight_smile:
I have been looking for an item like this for the past few days and couldn't find it but somehow figured to make my setup work and thought some people might find it helpful as well so here it is..

When configuring a two channel relay module (link ) it's nice to control both the ON as well as OFF time of both channels simultaneously. There are plently examples online in which this is done by delay() but this doesn't provide individual control of each channel.

Hope this helps:

const int RELAY1 = A0; //definition of channel 1 data pin.
const int RELAY2 = A1; //definition of channel 2 data pin.
int RELAY1State = LOW; //initial state of channel 1.
int RELAY2State = LOW; //initial state of channel 2.
const unsigned long interval1[] = {1000, 5000}; //time ON, time OFF.
const unsigned long interval2[] = {2000, 2000}; //time ON, time OFF.

unsigned long previousMillis1 = 0; //setting channel 1 millis() timing to 0.
unsigned long previousMillis2 = 0; //setting channel 2 millis() timing to 0.


void setup() {
  pinMode(RELAY1, OUTPUT); //initiate channel 1.
  pinMode(RELAY2, OUTPUT); //initiate channel 2.
}

void loop() {
  unsigned long currentMillis = millis(); //time as stored value.

  if (currentMillis - previousMillis1 >= interval1[RELAY1State]) 
    {
    previousMillis1 = currentMillis;
    if (RELAY1State == LOW) 
    {RELAY1State = HIGH;} 
    else {
      RELAY1State = LOW;
    }
      digitalWrite(RELAY1, RELAY1State);
  }

  if (currentMillis - previousMillis2 >= interval2[RELAY2State]) 
    {
    previousMillis2 = currentMillis;
    if (RELAY2State == LOW) 
    {RELAY2State = HIGH;} 
    else {
      RELAY2State = LOW;
    }
      digitalWrite(RELAY2, RELAY2State);
  }

}

This is not a tutorial. Please ask a moderator to move it to an appropriate "Showcase" sub forum.

2 Likes

I think it is. Am I missing something?

It does not give much explanation as to the how and why, though.

2 Likes

Hello hedur
Many thanks for your tutorial.
Add some comments to explain the functionality of the sketch.

1 Like

Under the Using millis() for timing. A beginners guide tutorial there's a link to Demonstration code for several things at the same time

From your title, is this more about how relays work like LEDs or about doing custom timing?

Hi DaveX, thanks for your remark. It's meant to be an easy template to use for a two channel relay with parallel intervals rather than subsequent intervals. :v:

You should factor the repetitive code. Imagine what it would look like, with 8 relays...

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.