The following code does what I need it to do (when a start switch is on and door switch is off - a warning light flashes. When the start switch and door switch are both on - a valve opens to allow water in for 2 seconds). I need the light to flash until the door is HIGH too at which point the valve program runs once. The only way I have to get out of this is to use exit(0). Is there a better way to do this? Ideally, I would like to stay away from anything too Boolean! Thank you.
int start = 2;
int door = 3;
int light = 8;
int valve = 9;
int counter = 0;
void setup() {
pinMode(start,INPUT);
pinMode(door,INPUT);
pinMode(light,OUTPUT);
pinMode(valve,OUTPUT);
}
void loop() {
if(digitalRead(start)==HIGH && digitalRead(door)==HIGH) {
digitalWrite(valve, HIGH);
delay(2000);
digitalWrite(valve,LOW);
exit(0);
//breaks out of loop. Arduino then needs reset.
}
if (digitalRead(start)==HIGH && digitalRead(door)==LOW) {
digitalWrite(light,HIGH);
delay(500);
digitalWrite(light,LOW);
delay(500);
}
}
1 Answer 1
What you need to do is learn what a finite state machine (FSM) is.
An FSM is a way of having the Arduino in one of a finite number of states, such as "light flashing", or "letting water in", etc.
I have written a reasonable (IMHO) tutorial here: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/
exit(0)
, withdelay(3000)
will do about the same thing. I think want you want is to remember that the valve has already been opened, on not open it again while both button are being pressed.while(1){}