3048 views|2 replies

27

Posts

0

Resources
The OP
 

The role of the volatile keyword [Copy link]

 

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

volatile unsigned int i;

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.

This post is from TI Technology Forum

Latest reply

Please go deeper.   Details Published on 2020-1-22 19:33
 

2618

Posts

0

Resources
2
 

Nice sharing, thank you.

This post is from TI Technology Forum
 
 
 

1310

Posts

3

Resources
3
 

Please go deeper.

This post is from TI Technology Forum
Personal signature

RTEMS

 
 
 

Guess Your Favourite
Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list