C Global declared in ISR

486 views Asked by At

I am evaluating Freescale's Kinetis Design Studio for their ARM series microcontrollers. I was looking at an example as a basis to do my first "blink an LED" project. When using variables shared between my main program and an ISR such as a counter, I would typically define a volatile global in main.c and reference it as extern in the ISR. Their example shows it exactly the opposite and they also don't use the volatile keyword. I have never seen it done this way. Is there an advantage to this? BTW, my program works just fine either way.

2

There are 2 answers

0
Clifford On BEST ANSWER

The missing volatile is an error (albeit a common one) that itself should be a quality warning. The choice of where to instantiate a global is arbitrary, but from a cohesion point of view, it makes sense to keep data that relates to the interrupt with the interrupt. That said, the use of the global data is itself an indication of dubious quality and practice.

A better pattern that makes use of data encapsulation is:


interrupt.c

...

volatile static int counter = 0 ;
void interruptHandler()
{
    counter++ ;
}

int interruptCounter{ return counter } ;

...

interrupt.h

...

extern int interruptCounter() ;

...

main.c

#include "interrupt.h"

    ...

    int icount = interruptCount() ;

    ...
7
too honest for this site On

I do not know the codewarrior suite. However, in general, volatile tells the compiler the variable is changed outside normal control flow as given by the program code.

Historically, embedded compilers were quite forgiving about not using 'volatile' and/or implemented some strategies to support inexperienced programmers who did not know about optimizations and "forgot" volatile. This will result, however, in badly optimized code, expecially for the ARM platform (it was less of a problem with HC08&Co MCUs which had to load every variable from memory anyway).

While it might be that CW is still that tolerant, compilers which highly optimize code like gcc are not that forgiving and optimise much more radical. If you forget volatile or barriers for such compilers, you might end up with an empty main-loop, for instance.

Even if your code runs fine for now, this might change once you enable optimizations or change a minor (possibly unrelated) aspect.

Very well meant advice from an long-term embedded developer: use volatile. Use it sparsely and well thought (more details can be found here), but use it!