循环 "while" 不满足中断的两个条件

Loop "while" is not satisfying both conditions with interrupt

我正在等待 AVR 或 STM32 MCU 上的真实事件(例如,按下按钮 3 秒),但我遇到了类似代码的问题:

#define PRESS_BUTTON
int waiting = 0;
int t_ms = 0; // time counter
//...

int main(void)
{           
    while(1)
    {           
        waiting = t_ms + 3000; // waiting button 3 sec

        while ((t_ms < waiting) && (!PRESS_BUTTON)) // infinite loop
        {}                  
        printf("out"); // not printed
        waiting = t_ms = 0;
    }    
}

ISR( TIMER0_OVF_vect ) // timer interrupt
{
    t_ms++;
}

但是如果我在 while 循环中添加一个 printf(),它就可以工作了!

如果我使用 do...while 循环,也会发生同样的事情。这是什么原因造成的?

您需要使用 volatile

声明 t_ms
volatile int t_ms =0;

Volatile 告诉编译器变量可能会因外部因素而改变,因此编译器永远不会假设它会保持不变。

换句话说,它将强制编译器检查每个循环以查看 t_ms 是否已更改,而不是假设它永远不会更改。