cstm32ldiscovery

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

//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;" and see "hello" again but nothing of this happens. If i insert the delay inside the loop all the expected is fulfilled


Solution

  • 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. Try declaring it as volatile.

    EDIT: Posting deleted answer back, for reference, since the OP has accepted in comments that this was the solution to his problem.