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

How can I use a global variable in the Interrupt routine?

The variable is defined in *.h:

static unsigned char cPwLe[3] = {0};

Its value is changed in the Main():
cPwLe[cCh] = Power_Level(cP[cCh]);  //Here  value is right

Its value is transfered to T0 Interrutpt service routine:
cPower = cPwLe[cCh]; //Here value is  always 0

How can I correct the errors?
Thanks all!

Parents
  • If the distinction between these two terms isn't clear to you, stop what you're doing right now, and get back to that C textbook.

    Hans-Bernhard,
    Are you actually suggesting that one need to know what one is doing? You are totally out of step with the times and must be very old. This is totally out of fashion these days.

Reply
  • If the distinction between these two terms isn't clear to you, stop what you're doing right now, and get back to that C textbook.

    Hans-Bernhard,
    Are you actually suggesting that one need to know what one is doing? You are totally out of step with the times and must be very old. This is totally out of fashion these days.

Children
  • If the reason you have a global variable is that some routine other than the interrupt handler uses the value, then you need to declare the global volatile (as well as extern).

    If only the interrupt handler uses the global variable -- that is, the variable is global only so that it preserves state between interrupts -- then you should probably remove the reference from the header file and declare the variable static so that no other routine can access the variable. You also might consider making the variable a static local, declared inside the interrupt handler.

  • Can you tell why?
    Just a MOD caculating result in the mistake:

    if (cC%(cPower+1)==0)
    ...
    
    When be corrected to if (){} and add statement,that variable work well.


    To my surprise,
    In the same routine,another global variable cSV which value be changed in UART_INT Service routine,can be used in MOD caculating orderly:
    if (cC%(cSV+1)==0)
    ...
    

    Thanks everyone!

  • Can you tell why?

    No. Nor can anybody else, from what you wrote. You're not giving anywhere nearly enough information for that.

    Just a MOD caculating result in the mistake:

    In what mistake?

    When be corrected to if (){} and add statement

    There's nothing to be corrected about what you wrote --- ripped completely out of context as it is, it's impossible for anyone not sitting on your chair to find out what "correct" might possibly mean, for this snippet of code.

  • Study the meaning and use of the volatile keyword. Code generated for the main routine might not use the latest value of a variable updated by an ISR unless that variable is declared volatile.