Hi,

Chris Liechti wrote:

michael_v_truong wrote:

- Right now I'm having trouble with global variables. I defined a variable in one of my headerfiles. My main program can change and manipulate that variable, but if I manipulate it in the interrupt, I can confirm that change in the interrupt, but once I return to main, the variable reverts back to its previous state (before the interrupt).


try: volatile int myglobalvar;
gcc optimizes variable usage and loads them into a register e.g. in a loop. if the variable can change from the outside, while running a function, you have to declare it as volatile.

There is a good point to note here, which catches a lot of people out. GCC is a pretty smart compiler. It will seek out and remove a lot of redundancy. However, this means the programmer has to be more exact about what they write. You can be pretty sloppy writing for IAR, as it fails to optimise away a number of redundant things GCC will. If something is volatile, you'd better make darned sure you declare it as such, or you will have problems. This is not a GCC issue, but a good compiler vs rather average compiler issue. If the main code keeps things in registers for efficiency, the interrupt code may not see an up to date value when reading from the copy in RAM. Similarly, if the interrupt code updates the copy in RAM, and the main code may overwrite this later when the interrupt returns. I think I should put this in the FAQ, as issues of this type regularly come up.

Regards,
Steve


Reply via email to