Stuck in while loop arduino

。_饼干妹妹 提交于 2020-01-16 14:49:51

问题


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();
  }
}


来源:https://stackoverflow.com/questions/55909270/stuck-in-while-loop-arduino

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!