This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Problem with global variables and Interrupt Service Routines

Hi!

I've many interrupt service routines on my current project! But I didn't
succeed in passing data between the main function and the ISRs!

I declared global variables (no difference if static or not), but when the
ISR is invoked, the value of the variables is 0xFF (unsigned char) oder
0xFFFF (unsigned int)!

On the compiler the "small" memory model is selected!

Any idea, what's wrong?

Have a nice day!
SVEN

  • Globals are usually evil but if you do use them to share data or control between the main line code and an ISR, be sure to declare them volatile. Usually, only one C file has a need for such a variable so you should limit the variables scope with the static keyword so they are not project global.

    volatile static unsigned char s_rdIdx;
    volatile static unsigned char s_wrIdx;
    
    void uartIsr(void) interrupt UART using 1
    {
        if (RI)
        {
            RI = 0;
            if (s_wrIdx == s_rdIdx)
            { 
                 // Ring is full
            }
         }
    }
    
    int getchar(void)
    {
        char inChar;
    
        // Wait while ring is empty.
        while (s_rdIdx == s_wrIdx);
    
        ...
    
        return (int) inChar;
    }

    - Mark