内部 for 循环被忽略

Inner for-loop is ignored

我正在尝试使用 Code Composer Studio 的 MSP-EXP430G2 教程程序来使 LED 闪烁。最初,它有一个闪烁的无限循环:

   for(;;)
    // This empty for-loop will cause the lines of code within to loop infinitely

        {

            P1OUT ^= 0x01;
    // Toggle P1.0 using exclusive-OR operation (^=)

    // P1OUT is another register which holds the status of the LED.
    // '1' specifies that it's ON or HIGH, while '0' specifies that it's OFF or LOW
    // Since our LED is tied to P1.0, we will toggle the 0 bit of the P1OUT register

            for(i=0; i< 20000; i++);

    // Delay between LED toggles. This for-loop will run until the condition is met.
    //In this case, it will loop until the variable i increments to 20000.
        }
    }

这是从教程中复制和粘贴的,并且按预期工作。然后我想看看我是否可以让它成为一个有限循环,所以我将 for 循环更改为:

for (j = 0; j<10; j++)

在代码前面声明了 j。但是,LED 不再闪烁,当我使用调试器单步执行程序时,它现在完全跳过了 for(i=0; i< 20000; i++); 行。这仅在我设置 j<10 条件时发生,但如果我将其设置为 j>-1 则不会。当我进行从 10 到 0 的递减循环时,会发生同样的问题,这让我认为它只发生在循环有限时。

我是不是遗漏了什么明显的东西?

允许编译器在没有副作用的情况下优化代码。内部 for 循环,其中计数器递增且之后不使用是此类代码的示例。

为避免这种行为,请在循环中引入副作用。一种方法是将 i 声明为 volatile。然后编译器将在每次更改后强制将 i 的值写回内存,并且循环将 运行 确切的次数直到条件变为 false。

或者,嵌入式平台或编译器通常提供 delay() 和/或 sleep() 函数。使用这些而不是忙循环是一种更好的编码实践——首先,无论硬件和 MCU 速度如何,您都将获得更多确定性的执行时间。

考虑使用 delay() 或 sleep() 而不是内部循环。