Hi there!
I have 8 relays that I need to turn on and off when 4 different PIR-sensors is active.
The relays turn on/off in pairs controlled by one PIR sensor.
I wrote a function that works fine when I just run it once. But the problem starts when I use the function twice. I can understand why it does not work but how should I tackle this problem?
Should I have more arguments in the function? Maybe one argument for the "previousMillis" and "interval"?
Here is the code:
int relayState = HIGH; // relayState used to set the relay
int relayState2 = HIGH;
unsigned long previousMillis = 0;
const long interval = random(1000, 3000);
unsigned long previousMillis2 = 0;
const long interval2 = random(1000, 3000);
void setup() {
Serial.begin(9600);
// Sensors
pinMode(2, INPUT);
pinMode(3, INPUT);
pinMode(4, INPUT);
pinMode(5, INPUT);
//Relays
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
pinMode(A0, OUTPUT);
pinMode(A1, OUTPUT);
digitalWrite(8, relayState); // I know that I can use a loop here but I do not remeber how...
digitalWrite(9, relayState);
digitalWrite(10, relayState);
digitalWrite(11, relayState);
digitalWrite(12, relayState);
digitalWrite(13, relayState);
digitalWrite(A0, relayState);
digitalWrite(A1, relayState);
}
void loop() {
minFunkMillis2(5, A0, A1); // This function runs fine if I run it once in the void loop
minFunkMillis2(4, 12, 13); // But it does not work when I run the function twice or more. I can understand why but how to solve the problem?
delay(10);
}
void minFunkMillis2(int sensor, int relay, int relay2) {
unsigned long currentMillis = millis();
int sensorState = digitalRead(sensor);
if (sensorState == HIGH){
//This is the code for the int relay:
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the relay
previousMillis = currentMillis;
// if the relay is off turn it on and vice-versa:
if (relayState == HIGH) {
relayState = LOW;
Serial.print("sensor:");
Serial.println(sensor);
Serial.print("relay:");
Serial.print(relay);
Serial.println(" is high");
} else {
relayState = HIGH;
Serial.print("relay:");
Serial.print(relay);
Serial.println(" is LOW");
}
// set the relay with the relayState of the variable:
digitalWrite(relay, relayState);
}
//This is the code for the int relay2:
if (currentMillis - previousMillis2 >= interval2) {
// save the last time you blinked the relay
previousMillis2 = currentMillis;
// if the relay is off turn it on and vice-versa:
if (relayState2 == HIGH) {
relayState2 = LOW;
Serial.print("relay:");
Serial.print(relay2);
Serial.println(" is high");
} else {
relayState2 = HIGH;
Serial.print("relay:");
Serial.print(relay2);
Serial.println(" is LOW");
}
// set the relay with the relayState of the variable:
digitalWrite(relay2, relayState2);
}
} else{
digitalWrite(relay, HIGH);
digitalWrite(relay2, HIGH);
}
}
I hope that I can get some advices here.
/Joel