loading

Multiple if statements arduino?

Hi everyone,
I'm very new to the arduino environment and am having trouble writing some code. 
Essentially what I need to do is turn on a relay for different periods of time based on different input. 
For example, 

If pin 8 is high, turn on relay for 5 minutes
if pin 9 is high, turn on relay for 10 minutes
if pin 10 is high, turn on relay for 20 minutes
if pin 11 is high, turn on relay for 30 minutes

There will be only one relay in the circuit. I.e. each pin will turn on the same relay, but for different amounts of time. 

I'm not quite sure the best way to do this. 

Thanks for you help in advance! 
Pete

bwrussell2 years ago

How/when are you wanting the inputs to be checked? mpilchfamily's stacked ifs will check the first one and then regardless of the result will check the second, third, etc. if statements. This means if pin8 was high that after the 300000 delay pin 8 won't trigger again until all the other pins have been checked. This delay in response will be very, very short if your code is short but the more ifs you put in the longer until each checked if can be rechecked. This may be acceptable/desired if not consider using if/else if.

if pin8 == HIGH
{
digitalWrite(relaypin, HIGH);
delay(300000);
digitalWrite(relaypin, LOW);
}


else if pin9 == HIGH
{
digitalWrite(relaypin, HIGH);
delay(600000);
digitalWrite(relaypin, LOW);
}


else if pin10 == HIGH
{
digitalWrite(relaypin, HIGH);
delay(300000);
digitalWrite(relaypin, LOW);
}

etc.

In this case after any one of the statements is true and it's code is run the entire block exits. If this was the end of your code then it would loop and start checking from the top again. Also closing the relay is important but could be done in one line after the loop block if using if..else.

verence2 years ago

Check all pins first, then switch on for the longest time (if that is, what you want, your description is not very clear. e.g. you didn't say what should happen if two pins are high). Something like: (syntax may be off, I don't have an Arduino around)

int timeOn = 0;
if (pin8 == HIGH) timeOn=5;
if (pin9 == HIGH) timeOn=10;
if (pin10 == HIGH) timeOn=20;
if (pin11 == HIGH) timeOn=30;
if (timeOn>0)
{
digitalWrite(relaypin, HIGH);
delay(timeOn*1000*60);
digitalWrite(relaypin, LOW);
}

if pin8 == HIGH
{
digitalWrite(relaypin, HIGH);
delay(300000);
}

if pin9 == HIGH
{
digitalWrite(relaypin, HIGH);
delay(600000);
}

You should have a good idea of what is needed now. Obviously yuor code will vary slightly. Just wanted to break it down enough that you could figure it out on your own.