Stuck in while loop arduino

2019-08-18 11:28发布

问题:

Here is my while main loop

void loop () {

  s4state = digitalRead(11); //Lit pin 11 switch

  if (s4state == 1) {  // wargning/detrese
    detresse(1);
  }
  if (s4state == 0) {  // wargning/detrese
    detresse(0);
  }
}

And here is the function I want to call.

void detresse(int valeurPin) {
  while(1==valeurPin) {
  digitalWrite (2, HIGH) ;
  digitalWrite (3, HIGH) ;
  digitalWrite (4, HIGH) ;
  digitalWrite (5, HIGH) ;
  digitalWrite (6, HIGH) ;
  digitalWrite (7, HIGH) ;

    delay (500) ;

    digitalWrite (2, LOW) ;
    digitalWrite (3, LOW) ;
    digitalWrite (4, LOW) ;
    digitalWrite (5, LOW) ;
    digitalWrite (6, LOW) ;
    digitalWrite (7, LOW) ;

    delay (500) ;
  }
}

But for some reason when I switch the pin too off the ligth keep turning on and off. I do not understand why I am stuck is this loop. How can I escape from it?

回答1:

But for some reason when I switch the pin too off the ligth keep turning on and off. I do not understand why I am stuck is this loop. How can I escape from it?

The loop doesn't break because the input to void detresse(int valeurPin) is not going to change. That is to say, once it is called, the state of the switch has no effect on that function and it will run in the while loop endlessly. What you can do is change up detresse like so:

void detresse(void) {
  digitalWrite (2, HIGH) ;
  digitalWrite (3, HIGH) ;
  digitalWrite (4, HIGH) ;
  digitalWrite (5, HIGH) ;
  digitalWrite (6, HIGH) ;
  digitalWrite (7, HIGH) ;

    delay (500) ;

    digitalWrite (2, LOW) ;
    digitalWrite (3, LOW) ;
    digitalWrite (4, LOW) ;
    digitalWrite (5, LOW) ;
    digitalWrite (6, LOW) ;
    digitalWrite (7, LOW) ;

    delay (500) ;
}

Also, you are calling this function regardless of the state of the switch, which is not what you want because the lighting sequence will be triggered regardless of what you are doing with the switch. Since there can only be two states for the switch, you should only call detresse on the either one or the other, not both. Assuming you want positive logic, this will make loop look like this:

void loop () {

  s4state = digitalRead(11); //Lit pin 11 switch

  if (s4state == 1) {  // wargning/detrese
    detresse();
  }
}


标签: arduino