## Friday, November 21, 2008

### To volatile or not to volatile - Part 2

Hamlet did know about volatile. He just ignored it.

Recalling Hamlet's action on volatileness and the previous post we can 'trick' the compiler when working with ISRs and no nested interrupts enabled.
We can't undeclare a variable or remove the volatile specifier once it has been written before on the same file. However we can write our ISR code in a different source file and declare the variables as global, volatile in the file that uses it outside the ISR and non volatile inside the file containing the ISR.
Here is the resulting code:

// ----- FILE: non_isr.c ------- //volatile unsigned int var1,var2;/** Just to use the variables as volatile * If Enter_Critical() and Exit_Critical() are * global functions then the volatile specifier above * could be avoided too */unsigned int getIntSum(void){   unsigned int temp;   Enter_Critical();      temp = var1 - var2;   Exit_Critical();   return temp;}//----------------------------------// ----- FILE: isr.c ------- //unsigned int var1,var2;void  ISR_Handler(void){   // do something with var1 and var2   // nested interrupts not enabled,   // thus it's secure to use them as normal variables}

A big disadvantage when doing this is that variables will be global and we can't declare them static since they have to be shared between several source files.
As said in the previous post, it's only a matter on what you need in that specific situation. In some cases the ISR will result in less execution time but in some others it might be the same or only a small performance boost.

#### 1 comment:

1. Very instructive. You should write the embedded version of "Expert C Programming".