简体   繁体   English

仅当条件为false且插入了延迟时,while循环才会停止

[英]while loop stops just when condition is false and a delay is inserted

i want to execute a while loop until a condition is reached, the condition is given by an interrupt fired with a user button, but when i press the button the while loop does not ends, the strange is that if i put a delay inside the loop then it works 我想执行一个while循环直到达到条件,该条件由一个用用户按钮触发的中断给出,但是当我按下按钮时while循环并没有结束,奇怪的是,如果我在循环然后工作

//does not works:
while( 1 )
{
 PRINTF("hello\n\r");

 while (button_state==0)
  {
   //do something
   if(button_state==1)
   break;
  }

button_state=0;
}
//works:
while( 1 )
{
 PRINTF("hello\n\r");

 while (button_state==0)
  {
   HAL_Delay(500);//i don't know why needs this to work
   //do something
  }

button_state=0;
}
//does not works:
while( 1 )
{
 PRINTF("hello\n\r");

 while (button_state==0)
  {
   //do something
  }

button_state=0;
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
  button_state = 1;
}

the program starts with a "hello", then goes into the while loop, i press the button and in this point the interrupt puts button_state to 1 and i expect that the while loops ends, reach the line where i reset the condition "button_state=0;" 程序以“ hello”开始,然后进入while循环,我按下按钮,此时中断将button_state设置为1,我希望while循环结束,到达我将条件重置为“ button_state = 0;” and see "hello" again but nothing of this happens. 并再次看到“你好”,但没有任何反应。 If i insert the delay inside the loop all the expected is fulfilled 如果我在循环中插入延迟,则所有预期都已实现

If it your variable button_state isn't declared volatile, the compiler might try to optimize away accesses to button_state within while (button_state==0) {} causing unexpected behaviour. 如果您的变量button_state未被声明为volatile,则编译器可能会尝试在button_statewhile (button_state==0) {}优化对button_state访问,从而导致意外行为。 Try declaring it as volatile . 尝试将其声明为volatile

EDIT: Posting deleted answer back, for reference, since the OP has accepted in comments that this was the solution to his problem. 编辑:张贴删除的答案回来,以供参考,因为OP在评论中接受了这是他的问题的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM