Could I simplify this code?

I'm playing with some sloenoids.... Got this scriot working, but I believe there is an easier way to write it.. Is there?
cheers!

int RelayPin1 = 1;
long RelayInterval1 = 200;
long previousMillis1 = 0;
int value1 = LOW;

int RelayPin2 = 2;
long RelayInterval2 = 120;
long previousMillis2 = 0;
int value2 = LOW;

int RelayPin3 = 3;
long RelayInterval3 = 340;
long previousMillis3 = 0;
int value3 = LOW;

int RelayPin4 = 4;
long RelayInterval4 = 600;
long previousMillis4 = 0;
int value4 = LOW;

int RelayPin5 = 5;
long RelayInterval5 = 160;
long previousMillis5 = 0;
int value5 = LOW;

int RelayPin6 = 6;
long RelayInterval6 = 180;
long previousMillis6 = 0;
int value6 = LOW;

int RelayPin7 = 7;
long RelayInterval7 = 360;
long previousMillis7 = 0;
int value7 = LOW;

int RelayPin8 = 8;
long RelayInterval8 = 340;
long previousMillis8 = 0;
int value8 = LOW;

void setup()
{
pinMode(RelayPin1, OUTPUT);
pinMode(RelayPin2, OUTPUT);
pinMode(RelayPin3, OUTPUT);
pinMode(RelayPin4, OUTPUT);
pinMode(RelayPin5, OUTPUT);
pinMode(RelayPin6, OUTPUT);
pinMode(RelayPin7, OUTPUT);
pinMode(RelayPin8, OUTPUT);
}

void loop()
{
if (millis() - previousMillis1 > RelayInterval1) {
previousMillis1 = millis();

if (value1 == LOW)
value1 = HIGH;
else
value1 = LOW;
digitalWrite(RelayPin1, value1);
}

if (millis() - previousMillis2 > RelayInterval2) {
previousMillis2 = millis();

if (value2 == LOW)
value2 = HIGH;
else
value2 = LOW;
digitalWrite(RelayPin2, value2);
}

if (millis() - previousMillis3 > RelayInterval3) {
previousMillis3 = millis();

if (value3 == LOW)
value3 = HIGH;
else
value3 = LOW;
digitalWrite(RelayPin3, value3);
}

}

I'm playing with some sloenoids.... Got this scriot working, but I believe there is an easier way to write it.. Is there?
cheers!

Yes. :smiley:

You probably want to write a function that accepts a number representing a particular relay and performs the appropriate actions. This will also mean you will want to set up an array to store the related values you need to keep track of, e.g. Pin number, interval etc

I would suggest going back to only one relay and write a function to operate that with the appropriate data stored in an array. Then add the other relays.

I'm being intentionally vague because I think it's better to work out a solution by yourself with guidance than to just get a prepackaged answer. :slight_smile: If that doesn't suit your purposes someone might be able to help you out with more detail.

--Phil.

Hi Follower. Thank you for being vage.. That's actually what I hoped for :slight_smile:
So, if i learn functions and arrays things would be shorter and cleaner....

Looking into it right now :slight_smile:
cheers!