This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

[参考译文] MSP430FR5969:关于在闪烁 LED 示例中使用 Volatile 的问题

Guru**** 1828310 points
Other Parts Discussed in Thread: MSP430FR5969
请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。

https://e2e.ti.com/support/microcontrollers/msp-low-power-microcontrollers-group/msp430/f/msp-low-power-microcontroller-forum/1429593/msp430fr5969-question-about-the-use-of-volatile-in-the-blink-the-led-example

器件型号:MSP430FR5969

工具与软件:

全部、

我对嵌入式编程很陌生、但我熟悉 C。我设法让 简单的闪烁 LED 示例适用于我的 MSP430FR5969  TI Launchpad。

#include <msp430.h>

void main(void)
{
    WDTCTL = WDTPW | WDTHOLD;               // Stop watchdog timer
    PM5CTL0 &= ~LOCKLPM5;                   // Disable the GPIO power-on default high-impedance mode to activate previously configured port settings
    P1DIR |= 0x01;                          // Set P1.0 to output direction

    volatile unsigned int i;                // volatile to prevent optimization
    //unsigned int i;

    for (;;)
    {
        P1OUT ^= 0x01;                      // Toggle P1.0 using exclusive-OR
        i = 10000;                          // SW Delay

        while (i != 0)
        {
            i--;
        }
    }
}

我对将 volatile 关键字 用于 I 有点好奇。 当我在没有 volatile 关键字的情况下进行尝试时、LED 根本不会闪烁、而是保持有效运行。 根据我在几个嵌入式相关网站上看到的内容、volatile 关键字用于这些情况。

  1. ISR 或多线程应用中的全局变量
  2. 存储器映射寄存器

然而、据我所知、我并不适合这些情况。 所以我有点困惑、不知道为什么编译器会对它进行优化。 是因为它在每个循环迭代中再次复位到10000吗?

谢谢!

Andy

  • 请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。

    如需更多信息、我还浏览了 CCS 调试器。 当我将 i 保持为 volatile 时、代码确实会进入 while 循环、从而导致 i 递减。 但当我离开易失性,它甚至没有递减 I

  • 请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。

    优化者有这种讨厌的习惯,注意到你在改变后不使用任何变量。 然后删除该代码。 由于"I"不在延迟环路之外使用...