Hey Gang!
I am three days into learning my programming for Arduino and I have hit a wall....repeatedly.
I am trying to program a timer to control four different pumps attached to relays. I would like each relay to cycle at separate time intervals from eachother. I need each relay timer to have an adjustable time on and time off. (i.e. 5 min on and 1 min off)
I have worked out a basic code and have them slightly working, but I have not had any luck finding resources to further my efforts. I would appreciate any constructive help in programming and explaining what I am doing right and or wrong. I would like to learn as much as possible about all of this. Of course, if someone is really bored and would create the code itself or an example for me to follow that would be great too! Please keep in mind that I am less than a week into all of this but not unfamiliar with electronics just the coding for Arduino.
I am using:
1 - Arduino Uno R3 board
1 - Quad relay module board (with opto-couplers)
1 - 5v usb power supply
Here is the code I have worked up so far as practice. (I have noticed my current code loses sync over about a minute. I do not understand why.)
//Cycle timer for quad relay module no delay function.
//Define relay pins
#define R1 7
#define R2 6
#define R3 5
#define R4 4
// DEFINE RELAY STATE
int R1State = LOW;
int R2State = LOW;
int R3State = LOW;
int R4State = LOW;
// Millis setup
long previousMillis1 = 0;
long previousMillis2 = 0;
long previousMillis3 = 0;
long previousMillis4 = 0;
//Interval setup
long interval1 = 2000;
long interval2 = 1000;
long interval3 = 500;
long interval4 = 250;
// Setup functions
void setup()
{
// Pin functions
pinMode (R1, OUTPUT);
pinMode (R2, OUTPUT);
pinMode (R3, OUTPUT);
pinMode (R4, OUTPUT);
}
// Loop Setup
void loop()
{
unsigned long currentMillis1 = millis();
unsigned long currentMillis2 = millis();
unsigned long currentMillis3 = millis();
unsigned long currentMillis4 = millis();
// Relay 1
if(currentMillis1 - previousMillis1 >interval1) {
previousMillis1 = currentMillis1;
if (R1State == LOW)
R1State = HIGH;
else
R1State = LOW;
digitalWrite(R1, R1State);}
// Relay 2
if(currentMillis2 - previousMillis2 >interval2) {
previousMillis2 = currentMillis2;
if (R2State == LOW)
R2State = HIGH;
else
R2State = LOW;
digitalWrite(R2, R2State);}
// Relay 3
if(currentMillis3 - previousMillis3 >interval3) {
previousMillis3 = currentMillis3;
if (R3State == LOW)
R3State = HIGH;
else
R3State = LOW;
digitalWrite(R3, R3State);}
// Relay 4
if(currentMillis4 - previousMillis4 >interval4) {
previousMillis4 = currentMillis4;
if (R4State == LOW)
R4State = HIGH;
else
R4State = LOW;
digitalWrite(R4, R4State);}
}
Cheers,
Will