LESSON 33: Understanding Local and Global Variables in Arduino

In lesson 32 we introduced you to the concept of Arduino Functions. Functions are little blocks of code that allow you to break a complicated task down into small logical chunks of code. All the parts of the program shared the same set of variables.  This is the easiest way to do functions, but is really not a good way of doing it. As programs get more complicated, with more functions, unexpected problems can arise if all the parts of the program are sharing the same variables. One function might inadvertently change a variable in use by another function causing unexpected problems. The best way to write modular code is to use local variables.

In Arduino, if a variable is declared at the top of the program, before the void setup, all parts of the program can use that variable. Hence, it is called a Global variable. On the other hand, if the variable is declared between a set of curly brackets, the variable is only recognized within that scope . . . that is, it will only be recognized and can only be used between that set of curly brackets.

For example, if a variable is declared in the void setup, it will not be recognized and can not be used in the void loop, because the void loop is within its own set of curly brackets.

Similarly, if there are two for loops inside the void loop, each for loop has its own set of curly brackets. If a variable is declared inside the first for loop, it will not be recognized inside the other for loop, and will not be recognized in the other parts of the void loop.

This might sound like a hassle, but using local variables really helps you stay out of trouble. The best way to do functions is to use local variable, and inside each function, the variables are declared that are needed by that function. Watch the video and I will give you clear examples of using local and global variables.