Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

specific use of volatile keyword

Status
Not open for further replies.

Fan174

Member level 2
Joined
Mar 27, 2018
Messages
51
Helped
0
Reputation
0
Reaction score
0
Trophy points
6
Activity points
413
Hello friends

volatile variable indicates that an object may be changed by something external to the program at any time and so must be re-read from memory every time it is accessed.

we can use volatile variable in interrupt


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<pic.h>
 
#define LED PORTD
  
void main(void)
{
    LED=0;
    TRISB0=1;
    TRISD=0;
    OPTION_REG=0X00;        //falling edge int @ enable pullup portb
    INTCON|=0Xd0;
    while(1) {
        LED=0x00;
    }
}
 
void interrupt  ISR(void)
{
    unsigned int i,j;
    LED=0X55;
    for(i=0;i<600;i++)
    for(j=0;j<200;j++);
    INTF=0;
}


How can be volatile variable useful in interrupt service routine ?
 

Volatile would be a hint to the compiler to re-read the variable because it could have been changed by the ISR. For example, if your main code was counting 'x' upwards and your ISR changed the value of 'x', it is possible that the compiler might optimize the code and not notice 'x' had been changed elsewhere. Bear in mind that the compiler might hold its value in a temporary variable while working with it. Making it volatile doesn't change its type or operation, it just tells the compiler not to optimize it and if necessary read its value again before carrying out any operation with it.

Brian.
 
I doubt that the code snippet is a useful application of interrupt service (e.g. when using delay loops inside the interrupt function), but it might at least show the problem handled by volatile.

From the main code viewpoint, code execution is staying in the while loop forever. Thus an intelligent compiler might "optimize" the code by executing LED=0x0 only once before entering the loop. Declaring LED as volatile would prevent this.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top