This content is originally created by EEWORLD forum user Min Da. If you want to reprint or use it for commercial purposes, you must obtain the author's consent and indicate the source
First, let’s look at a piece of code:
//P1.0 port connects to LED0 to make LED0 flash
#include <msp430.h>
int main(void)
{
WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer
unsigned int i;
P1DIR=0x01; //Define P1.0 port as output pin.
while(1)
{
P1OUT=0x01; //P1.0 outputs high level
for(i=5000;i>0;i--);
P1OUT=0x00; //P1.0 outputs low level
for(i=5000;i>0;i--);
}
}
|
Test results:
LED0 is always on
Why is this happening?
Modify the definition of variable i in the above code as follows, then burn and power on for testing
Test results:
LED0 flashes
Why does adding the volatile keyword solve the problem? What is the function of this keyword?
Volatile: Define a "volatile" variable. The compiler will assume that the value of the variable will change at any time, and any operation on the variable will not be deleted by the optimization process. In the actual programming process, the editor found that the software delay function generated by decrementing or incrementing the variable i will be optimized by the compiler and will not be executed. Therefore, if the reader encounters this situation and wants the delay function to work, just add the volatile keyword before the variable i.
Note: The above content is excerpted from "MSP430 MCU Principles and Applications - Introduction, Improvement and Development of MSP430F5xx/6xx Series MCU (Ren Baohong, Xu Kejun)"
Summarize:
The role of the volatile keyword. From the test results of Experiment 1, it can be concluded that both for loop statements are deleted by the compiler optimization process. In the actual while loop, only P1OUT=0x01;P1OUT=0x00;so the output result LED0 is always on. Through Experiment 2, the following conclusion can be drawn: The role of the volatile keyword is to tell the compiler that any operation of this variable (variable i) cannot be deleted by the optimization process and hope that the software delay function can work normally.