[英]while loop stops just when condition is false and a delay is inserted
我想執行一個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;
}
程序以“ hello”開始,然后進入while循環,我按下按鈕,此時中斷將button_state設置為1,我希望while循環結束,到達我將條件重置為“ button_state = 0;” 並再次看到“你好”,但沒有任何反應。 如果我在循環中插入延遲,則所有預期都已實現
如果您的變量button_state
未被聲明為volatile,則編譯器可能會嘗試在button_state
內while (button_state==0) {}
優化對button_state
訪問,從而導致意外行為。 嘗試將其聲明為volatile
。
編輯:張貼刪除的答案回來,以供參考,因為OP在評論中接受了這是他的問題的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.