Global Variables - I2C

Global variables are generally bad. The safest bet is to always avoid global variables whenever possible. They are difficult to debug and can be changed by any line of your code with few restrictions. That said, sometimes they are your only option, and in an I2C environment, the lack of flexibility when using interrupts necessitates the usage of global variables.

For interrupts, there are no “inputs” to the interrupt - nor should the interrupt “call” any function (unless that function is specific to the interrupt and can be executed as fast as possible). Any “communication” with the interrupt must be done via global variables or system registers.


For the scope of this project, you are required to declare any global variables used as static and volatile variables. For example:

static volatile char myChar;


{Developers note: I highly recommend you understand the difference between static and non-static variables with regards to file/library design in C. Static variables are local to the file or function they are declared in.... I.e. their scope is limited. Additionally their values are preserved through runtime. Non-static variables don’t have this specific restriction, but it also doesn’t guarantee their scope. Their values are also not preserved through scope.} 


Once again, using the fireman example: A global variable would be explained as a fireman's radio. When the fire is out, the fireman “radios back” informing the station chief that the fire was either successfully extinguished or there is another problem. Anyone with a radio would be able to hear that message, and any of them may also interact with their radios thus distorting the message.


Have you ever played with walkie talkies? If two people try to talk at the same time, the walkie talkie will either (best case) not produce any sound or (worst case) produce a screeching noise as the walkie talkie is trying to produce the combination of two sounds at once. 


In simple terms, global variables don’t guarantee the value is what you want it to be, at a specific point in time unless you restrict editing the global variables correctly (in our case, inside a function handler). The safest bet is to always avoid global variables whenever possible.