carmembeddedcortex-mcodewarrior

C Global declared in ISR


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.


Solution

  • 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() ;
    
        ...