1

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);
  }
}
  • I don't really see what the exit(0) does here. If the door and start buttons remain pressed, the valve will go open for 2 seconds, then close for a while, but then open again for 2 seconds, etc. The only thing exit(0) does is create a bit of a delay. So replacing exit(0), with delay(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. – Gerben Nov 27 '15 at 21:17
  • A better way to stop execution? Some trap the operation in an endless loop with a while(1){} – Dave X Nov 28 '15 at 5:17
  • I think the infinite loop is the best way. I have to teach this to High School kids who will only do a small part of programming as part of a course. I am trying to find Arduino solutions for questions that were originally designed for PBASIC (picaxe). There are a lot of questions which need the code to run once - and I need to restrict the commands to for, while, if....else commands ideally (in BASIC they would have used if/then, for/next and subroutines and that would be enough). – debkeys Nov 28 '15 at 14:56
  • What you made a mistake is instead of using "if"(first one) you had to use "while". And use the "if" to break out of the "while" using a "break" , what you have done is really a bad practice. – 25mhz Jan 9 '18 at 16:29
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/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.