Search code examples
cembeddedglobal-variablespic32

Sharing global variables with multiple Interrupt Service Routines in C


I am writing a program in C for PIC32 uC , that have a global variable(uint32_t type) that can be read/modified from multiple Interrupt Service Routines and from the main.
I know that is not safe so I was wondering how to make it safe ? Is there an example that show how to make it safe ?

Edit 1:

Can interrupts interrupt each other? yes
Does the ISR update the variable? yes Does main update the variable? yes Are writes and reads to the variable atomic and how do you know? Not sure
Is there a RTOS present? No


Solution

  • If you really need to keep global variables that can be modified during the servicing of several interrupts that can interrupt each other, I suggest you following way to do:

    1. Make all sequences of actions (read and/or write) on these variables "atomic" by disabling all interrupts before, then re-enable all interrupts after. On PIC32, you could do this by writing the global interrupt flag GIE.
    2. Declare these variables as volatile to avoid any unexpected optimization from compiler.
    3. Rename these variables with a specific prefix to identify them clearly, as Shared_XXXX, but it depends on the naming convention you are using.
    4. Put all sequences of actions on these variables in functions named with a specific prefix to identify them clearly, as Atomic_XXXX(). To implement the point 1: either these functions must all start by disabling all interrupts and end by reenabling all interrupts, or alternately you can systematically pass atomic functions as callback parameter to a function that will disable all interupts, call the callback function and reenables all interrupt.